SiHyung Lee
SiHyung Lee

Reputation: 349

How to use of KeyDown Event Validation in a better way?

I have several TextBoxes which need to allow only numeric inputs. The problem is I have to copy & paste the code below for another TextBox that allows only numeric values. Is there any simpler way to implement? such as using functions or inheritance?

private void txtCheckVoucher_Amount_KeyDown(object sender, KeyEventArgs e)
{
     if (Control.ModifierKeys == Keys.Shift)
     {
           e.SuppressKeyPress = true;
           return;
     }

     if (((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
             (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
              e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod ||
              e.KeyCode == Keys.Back || e.KeyCode == Keys.Tab ||
              e.KeyCode == Keys.Left || e.KeyCode == Keys.Right ||
              e.KeyCode == Keys.End || e.KeyCode == Keys.Home ||
              e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Delete))
     {

     }
     else if (e.KeyCode >= Keys.A || e.KeyCode <= Keys.Z)
              e.SuppressKeyPress = true;
}

Upvotes: 1

Views: 1219

Answers (4)

Sukanya
Sukanya

Reputation: 1061

You can call txtCheckVoucher_Amount_KeyDown() from all other text boxes' KeyDown event.

Upvotes: 1

Nighil
Nighil

Reputation: 4127

Simple Assign same KeyDown Event txtCheckVoucher_Amount_KeyDown() to all Textboxes

Upvotes: 0

Amar Palsapure
Amar Palsapure

Reputation: 9680

You can do this in three way

  1. You can have common function which will check the entered key is valid or not. And you call that function from all key down event handlers. This is suitable if you have textbox on different forms.
  2. If all the text boxes are on same form, in that case, bind all key down event handler to same function.
  3. You can have your custom textbox control which will accept only required keys. Check this post, it might help you.

In general, you can retrieve the textbox control id/name by ((System.Windows.Forms.Control)(sender)).Name

Hope this helps.

Upvotes: 3

itsme86
itsme86

Reputation: 19526

If the textboxes need the same KeyDown event logic, why not just subscribe both textboxes to the same event handler?

You can just set the KeyDown event to the same txtCheckVoucher_Amount_KeyDown() method.

Upvotes: 1

Related Questions