Thursday, 19 November 2009

C# Textbox with numbers only

I wanted to allow the user to modify the size of an image by entering a new width and heigth into textboxes. I was surprised to find that there was no really simple way of doing this like a property of the textbox (or maybe I missed it). This is how I solved it:

private void textBox_imageHeight_KeyPress(object sender, KeyPressEventArgs e)
{
int isNumber = 0;
if(!Char.IsControl(e.KeyChar.ToString().ToCharArray()[0]))
e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}

The IF statement checks for backspace and other control input.

No comments:

Post a Comment