Dear Sir,

I am using following codes on EVERY textbox.

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            decimal x;
            if (ch == (char)Keys.Back)
            {
                e.Handled = false;
            }
            else if (!char.IsDigit(ch) && ch != '.' || !Decimal.TryParse(textBox1.Text + ch, out x))
            {
                e.Handled = true;
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("Please enter Num 1");
                return;
            }
            else
            {
                textBox1.Text = Convert.ToDecimal(textBox1.Text).ToString("#,##");
            }
        }

In this way I have to waste much time and form space.

Is there any other way to use a routine on InitilizeCompent to handle all textboxes?

Please help

Use the sender object and eventually the 'as' keyword.
Sender is the object(textbox in your case) that generated the event.

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
        { TextBox Txb = sender as TextBox;
        etc.

Sir according to your advise you used these codes

private void Form1_Load(object sender, EventArgs e)
        {
            private void textBox_KeyPress(object sender, KeyPressEventArgs e)
            {
                TextBox Txb = sender as TextBox;
                char ch = e.KeyChar;
                decimal x;
                if (ch == (char)Keys.Back)
                {
                    e.Handled = false;
                }
                else if (!char.IsDigit(ch) && ch != '.' || !Decimal.TryParse(textBox1.Text + ch, out x))
                {
                    e.Handled = true;
                }
            }
        }

but it show following errors

Untitled.png

Untitled2.png

I think I am using code at wrong place, please guide me.

How many textboxes do you have on your form?
You get errors now because I guess yoor event handlers are all called Textbox1_KeyPress, Textbox2_KeyPress etc.
You only need ONE textbox_Keypress handler instead. If I run in a situation like this I also use an array instead of things like textbox1, textbox2 and so fort.
Can you try to work that out for yourself?
If not please return, DaniWeb will help as much as it can. :)

In VB.net you can assign a handler at run time with AddHandler. I think the c# equivalent is to assign it using New EventHandler(handler). Just loop through your textbox controls and voila.

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.