6
Reply

How to set TextBox to only accept numbers?

naouf gyd

naouf gyd

Nov 21 2015 1:36 PM
576
I have already checked other questions here but the answers are not related to my issue. the following code allows textbox1 to only accept numbers if the physical keyboard (laptop) is pressed:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if ( !char.IsDigit(ch))
{
e.Handled = true;
}
}
but this is not what I wanted (I dont use physical laptop keyboard).
I have windows form with buttons and a textbox1. I designed keyboard and it works well but I want textbox1 to only accept numbers and the ".".
There are only two lines of code inside each button (and only code in the project) which is:
private void buttonName_Click(object sender, EventArgs e)
{
// each button only has this code.
textBox1.Focus();
SendKeys.Send(buttonName.Text);
}
I know how to set textbox to accept numbers if the physical (laptop ) keys are pressed but here in this case I have windows form with control buttons ( each button to print its text into textbox1) and I want to set textBox1 to only accept numbers and the ".". Please help in how to achieve this. Thank you

Answers (6)