C# - Limit value in Textbox

Asked

Viewed 754 times

0

Hi, I’m wearing C#, and I’m having some trouble using a Textbox. I have a Textbox with this format: 192.168.100.1, to be more specific I’m putting IP numbers. inserir a descrição da imagem aqui

I would like from the second . (100) the number was not greater than 255 inserir a descrição da imagem aqui

I have tried using Substring and Length, but the bug program. Can someone help me???

  • The project is WebForm or Windows Forms?

  • I’m using Windows Form

1 answer

0


Suggestion 1

I recommend you use the component NumericUpDown. Include four of them in your form and seven properties minimum for 0 and maximum to 255.

The advantage of using this type of component is that you have control over the numbers you will receive, and you are sure that you will only receive numbers.

Suggestion 2

Use the component MaskedTextBox. Change the property mask for '999.999.999.999' and the property SkipLiterals for false.

To check the entered value, use the function:

    public static int verificaValor(string ip, int parte)
    {
//ip é o texto com o ip
//parte é qual das quatro partes você quer verificar
        if (parte == 1)
            return int.Parse(ip.Substring(0, 3));
        if (parte == 2)
            return int.Parse(ip.Substring(4, 3));
        if (parte == 3)
            return int.Parse(ip.Substring(8, 3));
        if (parte == 4)
            return int.Parse(ip.Substring(12, 3));
    }

This function will return the value of one of the 4 parts of ip, e.g.:

If ip is 192.168.100.1 and you use verificaValor(textBoxIp.text, 3); 100 will be returned.

So you can check the value using an if:

if (verificaValor(textBoxIp.text, 3) > 255)
    //mensagem de erro

Even so, I suggest the first way to do, as it prevents the user to enter values above what you want.

  • Thank you very much!!! It worked right, I just had to adapt to my code. Thanks!!!

  • you can also show your gratitude by giving a like in my reply and marking it as your chosen response (by clicking on the "check"). Hug

Browser other questions tagged

You are not signed in. Login or sign up in order to post.