Reputation: 20046
How to validate a TextBox
field against a Natural Number? User are restricted to input natural number (e.g. 1,2,3..99999) and if not, a MessageBox
is shown.
Currently I'm using the following code (assuming the natural number does not go beyond two digits):
Regex isPositiveNum2 = new Regex("[1-9]");
Regex isPositiveNum = new Regex("[1-9][1-9]");
if (isPositiveNum.IsMatch(textbox1.Text) == true ||
isPositiveNum2.IsMatch(textbox1.Text) == true)
{
/* Do something */
}
else
{
MessageBox.Show("Hey! This is not a Natural Number");
textbox1.Text = "1";
}
This works alright, but I'm sure it's not the best approach. Hope something can suggest something better.
Upvotes: 2
Views: 2580
Reputation: 8786
You can check the char while user entering:
Private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(!char.IsDigit(e.KeyChar)&&!char.IsControl(e.KeyChar)) //only digit but still allow the user to use control key to Copy&Paste etc. But you need to apply validating with paste text as well
{
e.Handled=true;
}
}
Upvotes: 1
Reputation: 1674
try this:
int myValue;
if (int.TryParse(mNumTb1.Text, out myValue) && myValue > 0)
{
//natural
}
else
{
//not natural
}
Upvotes: 3
Reputation: 499002
Use the built in parsing:
int.Parse(textbox1.Text) > 0
This will throw an exception if textbox1.Text
can't be parsed, so you may want to use TryParse
instead:
int test;
if(int.TryParse(textbox1.Text, out test))
{
// parse succeeded can check if natural
if(test > 0)
{
// do something
}
}
Upvotes: 2
Reputation: 27913
int number;
if (int.TryParse (textbox1.Text, out number) && number >0)
{
/* Do something */
}
else
{
MessageBox.Show("Hey! This is not a Natural Number");
textbox1.Text = "1";
}
Upvotes: 1
Reputation: 25277
int i = -1;
int32.TryParse(textbox1.Text, out i);
if (i > 0)
{
return true;
}
else
{
return false;
}
Upvotes: 1