0

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

Edited by phphp

3
Contributors
4
Replies
24
Views
1 Month
Discussion Span
Last Post by Reverend Jim
1

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.
0

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.

0

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

0

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.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.