Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textbox maximum/minimum numeric values C#

Tags:

c#

textbox

I want to create an if Statement that validates whether an input number in a textbox is between 0 to 100. For example:

NumericUpDown num = new NumericUpDown();

num.Maximum = 100;
num.Minimum = 0;

if (int.Parse(txtMid.Text) < num.Minimum && int.Parse(txtMid.Text) > num.Maximum)
{
    MessageBox.Show("Please input 0 to 100 only.");
}

That's all. Thanks in advance.


1 Answers

You need to parse the txtbox1.Text string into an integer:

int val = 0;
bool res = Int32.TryParse(txtbox1.Text, out val);
if(res == true && val > -1 && val < 101)
{
    // add record
}
else
{
    MessageBox.Show("Please input 0 to 100 only.");
    return;
}

Also, do you need to test one or two textboxes? If it's only one and you need the interval 0, 100, then your condition is wrong, because it always returns false (a number cannot be at the same time <= -1 and >= 101).

VERY IMPORTANT: I have reversed your if/else: you have to print the error in the else and add the record in the if.

like image 152
Tudor Avatar answered Jun 24 '26 23:06

Tudor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!