Integer TextBox

I created an application in C# for findng if the number entered by a user is Prime or Not,the logic part was ok.But I'm using Textbox for getting the number from user and complier is giving me errror that string cant be converted ....So I wanted to know how to use Textbox for getting the numbers and that Texbox should take only integer values.Help me out.Thanx

Answer this question

Integer TextBox

  • l99057j

    You can also use NumericUpDown control.

  • EppuTheHeppu

  • Lowell2002

    In regards to the numericUpDown control.

    I might be totally wrong with my assumptions but I believe the numberUpDown control has its value set as a decimal. So one has to convert its decimal value into an integer value.

    int number = Convert.ToInt32(numericUpDown1.Value);

    This will place the value of the numericUpDown1 control into an integer called number.

    By default the default Increment property of the numberUpDown1 control is 1 and when you try to enter a decimal number into the control it will automatically convert it to the nearest whole number.

    Hope this helps.

    Richard.


  • Adapterboy

    Thanx Boban,it would be just gr8 if you could please provide me the eaxmple,I mean the code syntax of how to use it.Thanx

  • Dan987

    Hi Srock,

    You can handle the KeyPress event of the TextBox like this;

    void tb_textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
    e.Handled = false;
    else
    e.Handled = true;
    }

    This way, the textbox only accepts numeric values (and backspace + delete)

  • Mike Pelton

    try { int number = int.Parse(textBox1.Text); textBox2.Text = "You entered " + number; }

    catch { textBox2.Text = "Error: You must enter an integer"; }

    My example isn't that good, but it assumes you try to enter an integer into textBox1. It will only set the textBox2.Text property to "You entered " and the number itself if you entered a valid integer. If not it will display an error message message.

    Hope this helps.

    Richard.


  • Integer TextBox