Restricting a windows textbox to digits only.

  • Thread starter Thread starter volume
  • Start date Start date
V

volume

Restricting a windows textbox (edit item) to digits only.

Is there a windows option, using .NET C#, to only allow a user to enter
digits ONLY? If so, what is the flag or setting? If no, what is the best
method to manually and robustly do it?

I have a windows form with an editbox that I only want user's to enter
digits.

Thanks in advance.
 
Hi volume,
you could capture the keypress event of the textbox and validate that the
character was a digit i.e.

private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.KeyPress += new
KeyPressEventHandler(textBox1_KeyPress);
}

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}

Hope that helps
Mark R Dawson
http://www.markdawson.org
 
You can use the Validating event to validate the contents of the TextBox.
User can't select anything and even not close the form while the contents is
not validated.


textBox1.Validating += new
System.ComponentModel.CancelEventHandler(textBox1_Validating);

private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
e.Cancel = !Regex.IsMatch(textBox1.Text, "[0-9]*");
}
 
Thanks all. They both worked ace.

Lebesgue said:
You can use the Validating event to validate the contents of the TextBox.
User can't select anything and even not close the form while the contents is
not validated.


textBox1.Validating += new
System.ComponentModel.CancelEventHandler(textBox1_Validating);

private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
e.Cancel = !Regex.IsMatch(textBox1.Text, "[0-9]*");
}

volume said:
Restricting a windows textbox (edit item) to digits only.

Is there a windows option, using .NET C#, to only allow a user to enter
digits ONLY? If so, what is the flag or setting? If no, what is the best
method to manually and robustly do it?

I have a windows form with an editbox that I only want user's to enter
digits.

Thanks in advance.
 
Back
Top