Click to See Complete Forum and Search --> : preventing non-ints in a string


sternaphile
November 6th, 2002, 11:23 AM
How do you do this in C#? I'm used to making an edit-box in VC, and forcing it to only accept int values. Can't seem to find the way to do this in C#.

Thanks,
sternaphile

bfarley
November 6th, 2002, 12:56 PM
Write a handler for KeyDown/KeyPress (not sure which, but one will work) in the text box. Check the value of the key. If not a number, stop processing i.e. .Handled()

Bill F

sternaphile
November 6th, 2002, 01:37 PM
Sure, that would work, but how about something along the lines of isdigit()?

bfarley
November 8th, 2002, 01:22 PM
As in using isdigit() to check the key? The KeyPress handler will return the key pressed. I'm sure there is a static function Keys.IsDigit() or some sort that could do that.

Bill F

CPCericola
November 8th, 2002, 07:52 PM
In your validation code(KeyPress or KeyDown), do the following:


private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((Char.IsDigit(e.KeyChar) == false) && (Char.IsControl(e.KeyChar) == false))
{
e.Handled = true;
}
}


That chesk for digits(0-9) and control keys(arrows, delete, etc). Hope that helps!