0

I've followed this guide

How do I make a textbox that only accepts numbers?

The method provided limits the characters we can input on the box

private void textBox18_KeyPress_1(object sender, KeyPressEventArgs e)
    {
         if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != ','))
        {
            e.Handled = true;
        }

        // only allow one decimal point
         if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
         {
             e.Handled = true;
         }
    }

it's working very well, but there's a catch, i have to add the event handler to 100+ text boxes. Is there a simpler way to do this? Since it envolves both the designer.cs and the cs.

I'm working on winform, visual c# 2010 express edition

Community
  • 1
  • 1
ng80092a
  • 77
  • 1
  • 1
  • 9

2 Answers2

1

You could simply do this in the FormLoad method:

textBox19.KeyPress += textBox18_KeyPress_1;
textBox20.KeyPress += textBox18_KeyPress_1;
textBox21.KeyPress += textBox18_KeyPress_1;
textBox22.KeyPress += textBox18_KeyPress_1;
textBox23.KeyPress += textBox18_KeyPress_1;
// etc
textBox999.KeyPress += textBox18_KeyPress_1;
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • I took a look and it uses a different "grammar", it goes like `this.textBox61.TextChanged += new System.EventHandler(this.textBox61_KeyPress_1);` @Enigmativity – ng80092a Nov 10 '14 at 02:01
  • You don't need the `new System.EventHandler`. The compiler figures it out without it. – Enigmativity Nov 10 '14 at 02:04
1

Rename your current textBox18_KeyPress_1 to something more descriptive.

eg. GenericTextBoxKeyPress

Then, in the constructor (after InitComponents) or Form Load, you may add these events to your textboxes one by one or using a loop.

//One by one
textBox1.KeyPress += GenericTextBoxKeyPress;
textBox2.KeyPress += GenericTextBoxKeyPress;
textBox3.KeyPress += GenericTextBoxKeyPress;

//All TextBoxes in your form
foreach(var textbox in this.Controls.OfType<TextBox>())
{
    textbox.KeyPress += GenericTextBoxKeyPress;
}

Alternatively, you could create a class that implements TextBox and override the OnKeyPress behavior. Then, change all your TextBoxes to use this new class.

using System.Windows.Forms;

namespace MyApplication
{
    class MyTextBox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != ','))
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if ((e.KeyChar == ',') && Text.IndexOf(',') > -1)
            {
                e.Handled = true;
            }
            base.OnKeyPress(e);
        }
    }
}
learningcs
  • 1,856
  • 16
  • 25