-1

I am fairly new to C#, and this is my first attempt at creating a windows form. I created a very simple calculator which has two textboxes for users to enter numbers into. It has a(n) Add, Subtract, Multiply, and Divide button, and when the user enters values into the textboxes and clicks one of the buttons, the result is shown in a label. I would like to only allow integers to be input into the textboxes, but I don't know how I would be able to do this. Any advice or recommendations are appreciated. Thanks.

Here is my code so far:

namespace SimpleCalc
{
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void AddBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
    }

    private void SubtractBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) - Convert.ToInt32(textBox2.Text)).ToString();
    }

    private void MultiplyBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text)).ToString();
    }

    private void DivideBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) / Convert.ToInt32(textBox2.Text)).ToString();
    }
}

}

4 Answers4

2

You can use the below Function, and add it for Key press event of the text box.

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

enter image description here

Prashanth kumar
  • 949
  • 3
  • 10
  • 32
0

Simplest way is to use the NumericUpDown control instead TextBox. NumericUpDown only allows numbers as their input and have similar properties of TextBox.

Access the value like this :

decimal answer=numericUpDown1.Value

`

Beingnin
  • 2,288
  • 1
  • 21
  • 37
0

Use NumericUpDown

You can find here a similar question How do I make a textbox that only accepts numbers?

Mhd
  • 2,778
  • 5
  • 22
  • 59
-1

make it simple try this

//function
public static void NumberOnly(object sender, KeyPressEventArgs e)
{
     e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}

//to call used this
NumberOnly("your textbox");
Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40