The WinForm textbox is a useful widget. You can enter just about anything into it. It is possible to set a flag and make it into a password entry box where all input is substituted for something else (such as an asterix). However, there is a limitation - you can't use it for numbers only. Okay, you could use a number up/down widget, but then there is a problem of having the up/down arrows.
There are two ways of using a textbox for numbers only. The first is to read the contents and use RegEx, but this is a bit of a pain and you have to understand RegEx. A much simpler method is to extend the Textbox class
class NumberBox : TextBox
{
public NumberBox()
{
this.CausesValidation = true;
this.Validating += new CancelEventHandler(TextBox_Validation);
}
private void TextBox_Validation(object sender, CancelEventArgs e)
{
try
{
int value = System.Int32.Parse(this.Text);
}
catch (System.Exception)
{
e.Cancel = true;
}
}
}
Pretty much, that's all there is to it - if you enter a number, all is well. Enter text and it won't let you
No comments:
Post a Comment