A
A
Alexander Sharomet2014-03-13 15:14:38
Programming
Alexander Sharomet, 2014-03-13 15:14:38

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

4 answer(s)
C
Codebaker, 2014-03-13
@sharomet

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!";
            }
        }

A
Alexander, 2014-03-13
@Papagatto

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;
        }

A
AlexP11223, 2014-03-13
@AlexP11223

NumericUpDown same
0acaaa7fcaf324d90e02c4c4cb8cc093.png

A
Alexander, 2014-03-14
@avorsa

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 question

Ask a Question

731 491 924 answers to any question