M
M
MrFlatman2018-05-06 22:04:29
C++ / C#
MrFlatman, 2018-05-06 22:04:29

Checking TextBox for numbers?

Recently there was a task to do work in Windows Form, I didn’t really work with them, so I ran into such a task. There is a TextBox, it is necessary to check whether the user entered at least something and whether the entered data is numbers, if not, then it is desirable to display the MassageBox with an error, or simply display an error in the same TextBox.
I did it very stupidly, just like this:

String^S1 = textBox1->Text;
    if (S1 == "") {
      MessageBox::Show("Вы не ввели значение А. Значение А принято как 0", "Ошибка!");
    }
    else {
      a = Convert::ToInt32(S1);
    }

I understand that this is not correct, I would like to know how best to do it so that it would not look so terrible

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alexalexes, 2018-05-06
@MrFlatman

In my student years, I wrapped it in a try catch:
If the converter collapses, then it was not a number, the conversion rolled, then a number.
Enough for educational needs.

S
Stanislav Makarov, 2018-05-06
@Nipheris

int.TryParse

A
Alexander Ter, 2018-05-07
@alexsandr0000

Why not use NumericUpDown ?
If using a TextBox is essential, then you can use, in addition to the above, Regex.IsMatch(input, @"^\d+$")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question