Hi guys.
I am trying to make a textbox that accepts only numbers and comma but no luck.
I did a search on the forum and found some snippets of code but still couldn't get it working.
I can't show you any of my code so far, because I don't have any yet, this textbox is my starting point.

Thanks

Add KeyPress event to the TextBox and use this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     int isNum = 0;

     if (e.KeyChar == ',')
          e.Handled = false;
     else if (!int.TryParse(e.KeyChar.ToString(), out isNum))
          e.Handled = true;
}

Hope that helps.

Thanks

Edited 6 Years Ago by farooqaaa: n/a

Thanks guys.
One more question if I may... I've used the code farooqaaa provided. Now that the textbox accepts only numbers I'm capturing the input using

private void textBox1_TextChanged(object sender, EventArgs a)
        {
            a = Convert.ToDouble(textBox1.Text);
            ....
        }

and then doing some maths by clicking on another button. The thing is that I would like to use negative numbers , but if I introduce minus (-) before the number the program crashes.
I found a way around by adding a checkbox that does

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            a = -a;
        }

but I thought there may be a better method...
Any ideas? :)

This question has already been answered. Start a new discussion instead.