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

Recommended Answers

All 3 Replies

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

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? :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.