I want to validate the input on a textbox on a Windows Forms application i.e. show a message box with an error if the number entered is lower than 1 or greater than 24 or if any other character besides an integer is entered. How would I go about doing this?
-
[WinForm UI Validation](http://stackoverflow.com/questions/769184/winform-ui-validation) – Ilya Ivanov Oct 28 '13 at 17:35
-
possible duplicate of [What is the C# equivalent of NaN or IsNumeric?](http://stackoverflow.com/questions/437882/what-is-the-c-sharp-equivalent-of-nan-or-isnumeric) – NotMe Oct 28 '13 at 19:34
5 Answers
I would consider something like:
//make sure that we have a valid number in the text box with no other characters
//loop through the string, examining each character
for (int i = 0; i < txtHour.Text.Length; i++)
{
//if this character isn't a number, then don't close the form or continue
if (!char.IsNumber(txtHour.Text[i]))
{
MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
return;
}
}
//now that we know we have a valid number, convert the string to int and make sure it's not less than 1 or greater than 24
int testInt = Convert.ToInt32(txtHour.Text);
if (testInt < 1 || testInt > 24)
{
MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
return;
}
For the method example that you asked for in your comment you could do something more like:
//////////////////////////////////////////////////////////////////////
//in your main code:
if (!isValidHour(textBox1.Text))
MessageBox.Show("Value for field must be a number from 1 to 24");
if (!isValidHour(textBox2.Text))
MessageBox.Show("Value for field must be a number from 1 to 24");
//////////////////////////////////////////////////////////////////////
///method to validate if text field is an INT from 1 to 24
bool isValidHour (string stringToValidate)
{
//make sure that we have a valid number in the text box with no other characters
//loop through the string, examining each character
for (int i = 0; i < stringToValidate.Length; i++)
{
//if this character isn't a number, then don't close the form or continue
if (!char.IsNumber(stringToValidate[i]))
{
//MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
return false;
}
}
//now that we know we have a valid number, convert the string to int and make sure it's not less than 1 or greater than 24
int testInt = Convert.ToInt32(stringToValidate);
if (testInt < 1 || testInt > 24)
{
//MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
return false;
}
return true;
}

- 1,048
- 2
- 10
- 22
-
Thanks, this works perfectly. To expand this for say validating input for 2-3 text boxes would it be a case of using the same block of code but changing the textbox name and creating a new int or is there a way of validating the input of multiple text boxes in the exact same was as above but in one block of code? – Oct 29 '13 at 03:08
-
@user2929108 - see new code block for one possible answer to this question – blitz_jones Oct 29 '13 at 14:05
-
the line `int testInt = Convert.ToInt32(stringToValidate);` throws a `FormatException` error – Oct 31 '13 at 14:30
-
@user2929108 - I can't reproduce your issue, and I don't have your code to comment on. The only issue I can find with the code block that I wrote above is that if the number in the textbox is more than 32 bits, there will be an overflow exception on Convert.ToInt32, but you could easily just add a try block or a char count to prevent that. If you don't show any of your own code, no one here will be able to tell you why you get a FormatException. Your question was already put on-hold and marked as off-topic (rightfully so) for this very reason. – blitz_jones Oct 31 '13 at 17:09
try{
if((int)item.value >= 1 && (int)item.value <=25){
//match.
}else{
//error.
}
}catch (Exception e){
//type error
}
//or---
var itemValue = default(int);
if(int.TryParse(item.value, out itemValue)){
if(itemValue >= 1 && itemValue <= 25){
//match.
}else{
//error.
}
}else{
//item.value is not numeric.
}

- 19,551
- 15
- 98
- 146

- 10,222
- 12
- 66
- 129
-
Should you use `int.Parse` here or even better `int.TryParse` ? What is the meaning of `catch` block here? – Ilya Ivanov Oct 28 '13 at 17:39
-
I put it in as an attempt to parse something that is not numeric. If the catch executes, it would mean that the input was not numeric. If you dont want to use the catch, the try parse would suffice doing the same thing. It would check to see if it is possible to parse it into a numeric. – Fallenreaper Oct 28 '13 at 17:45
-
1`TryParse` has a second parameter, marked as `out`. You don't need to parse `item.value` several times. The error would also be shown, if the value is not a number. – Ilya Ivanov Oct 28 '13 at 17:48
-
Hi. Thanks for the response although I'm not sure how to fit the code to my program. The textbox I want to apply this to is called `txtHour` – Oct 28 '13 at 17:51
-
I wouldn't even try the first example as it is quite possible that the `item.value` is a string and won't even cast. – IAbstract Oct 28 '13 at 19:36
You can add a private method and call it wherever necessary by passing textbox control which needs to be validated.
private void ValidateText(TextBox textbox)
{
int value;
bool isConverted = Int32.TryParse(textbox.Text.Trim(), out value);
if (!isConverted)
{
MessageBox.Show("Only numbers allowed");
return;
}
if (value < 1 || value > 24)
{
MessageBox.Show("Please enter a value between 1-24");
}
}
Validating txtHour by invoking above method
ValidateText(txtHour);

- 8,696
- 5
- 43
- 65
Look into doing your check with the OnKeyPress/OnKeyDown/OnKeyUp events:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

- 3,185
- 2
- 37
- 43
This is a very simplistic implementation but, this will achieve the validation that you are asking for:
int hoursEntered;
bool isInteger;
isInteger = int.TryParse(txtHour.Text, out hoursEntered);
if (hoursEntered < 1 || hoursEntered > 24 && isInteger == true)
MessageBox.Show("Your number is either less than 1, greater than 24 or you didn't enter a number", "Warning!", MessageBoxButtons.OK);
There are a few things to consider here though. I wrote this code and had it tied to the event handler for a button click. If that is not your implementation, then I would strongly consider using the OnKeyPress/OnKeyUp/OneKeyDown
events to do your validation. Otherwise, you can just copy this code into whichever button click event handler you already have in-place.

- 5,069
- 7
- 37
- 47
-
1The input "2a" would parse as 2...which would still be a failure according to the op. – NotMe Oct 28 '13 at 19:30
-
@ChrisLively - You are 100% correct. Unfortunately, I was called into a last minute meeting while posting the answer and didn't get to finish it up. Dizzy.stackoverflow has already posted the answer I was driving towards. – Brian Oct 28 '13 at 19:58