-1

I made a calculator that uses textboxes.

private void Btnrovnase_Click(object sender, EventArgs e)
    {

        int vysledek;
        vysledek = (int.Parse(textBox1.Text) / int.Parse(textBox2.Text));
        textBox3.Text = vysledek.ToString();

My code looks like this but now I want to use int named a in it.

The question is, is there a way to put the int in textbox1 or textbox2?

pppery
  • 3,731
  • 22
  • 33
  • 46
  • It is not clear. In a textbox you can write anything you like until you reach the MaxLength number of characters. Are you asking how to force your user to input only digits? – Steve Sep 16 '19 at 21:14
  • You should research data sanitization, since you are dividing two numbers into an integer which will not always happen and numbers may not even be used. – Greg Sep 16 '19 at 21:20

1 Answers1

0

If you want only digits and numbers, you can use a NumericUpDown control.

But if you want a TextBox, you can use KeyPress event:

private void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if ( !char.IsDigit(e.KeyChar) ) 
    e.Handled = true;
}

You can assign NumericTextBox_KeyPress to all desired TextBoxes.

If you want to handle things such as decimal separator you can use for example:

System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

Like that:

string separatorDecimal = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

if ( !char.IsDigit(e.KeyChar) 
  && new string(e.KeyChar, 1) != separatorDecimal )
  e.Handled = true;