Answer the question
In order to leave comments, you need to log in
How to check that textBox contains only numbers TextChanged C#?
Hello.
My question is: How can I prevent the user from entering everything except numbers in a textBox, and these numbers should be transmitted in real time to another textBox?
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text2.Text;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text1.Text;
}
Thank you!
Answer the question
In order to leave comments, you need to log in
private void textBox1_TextChanged(object sender, EventArgs e)
{
double num = 0.0;
if (double.TryParse(textBox1.Text, out num))
{
textBox2.Text = textBox1.Text;
}
else
{
textBox2.Text = "Only numbers, please!";
}
}
Add another keypress handler like this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//Цифры
if ((e.KeyChar >= '0') && (e.KeyChar <= '9'))
{
return;
}
//Точку заменим запятой
if (e.KeyChar == '.')
{
e.KeyChar = ',';
}
if (e.KeyChar == ',')
{
if (textBox1.Text.IndexOf(',') != -1)
{
//Уже есть одна запятая в textBox1
e.Handled = true;
}
return;
}
//Управляющие клавиши <Backspace>, <Enter> и т.д.
if (Char.IsControl(e.KeyChar))
{
return;
}
//Остальное запрещено
e.Handled = true;
}
If you need a TextBox, and not what is offered in the topic, then I do this
private void TextBoxCheckPeriodKeyPress(object sender, KeyPressEventArgs e)
{
//allows backspace key
if (e.KeyChar != '\b')
{
//allows just number keys
e.Handled = !char.IsNumber(e.KeyChar);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question