netpicker9

Hi.

How to validate a textbox for numerics

I tried like

If Not IsNumeric(txtYears.Text) Then
MsgBox("Year must be a numeric value", , My.Application.Info.Title)
txtYears.Focus()
Exit Sub
End If

and tried to input ".5" and IsNumeric returns "TRUE", why & what is the solution

Thanks




Re: Windows Forms General Numeric Validation

timvw

Why don't you use the NumericUpDown control instead It seems far more appropriate...

Anyway, to answer your question. The documentation for IsNumeric says:


IsNumeric returns True if the entire Expression is recognized as a number; otherwise, it returns False.

IsNumeric returns True if the data type of Expression is Short, Integer, Long, Decimal, Single, or Short. It also returns True if Expression is a String that can be successfully converted to a Double. It returns False if Expression is of data type Date.



The point is that .5 will be interpreted as 0.5, thus it returns true. (Btw, 10E3 would also be accepted, and interpreted as 1000)






Re: Windows Forms General Numeric Validation

netpicker9

Customer wants this as a textbox, thats the reason why I am using it.. Any other idea




Re: Windows Forms General Numeric Validation

DeborahK

You could check each key as the user types it and ensure each entered key is numeric.

Or you could leave the code where you have it - but have it check every character to ensure that it is 0-9.





Re: Windows Forms General Numeric Validation

timvw

Handling the KeyPress is a viable approach:

Code Snippet

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

{
int start = '0';
List<char> allowedCharacters = new List<char>();
for (int i = 0; i < 10; ++i)
{
allowedCharacters.Add((char)(start + i));
}

// allow the user to 'correct', thus allow backspace
allowedCharacters.Add('\b');

if (!allowedCharacters.Contains(e.KeyChar))
{
e.Handled = true;
}

}


(Other possibilities include using databinding, or using Int32.TryParse in the validating event)