0

Can we created common function to check keypress event and restrict user to enter only numeric entries for multiple textboxes in windows form?

Can we create something like below:

private void txtsample1_keypress(...)
{
  call validate()
}

private void txtsample2_keypress(...)
{
  call validate()
}

public void validate()
{
  Here, validation for multiple textboxes
}
Paresh J
  • 2,401
  • 3
  • 24
  • 31
  • 1
    have a look here: http://stackoverflow.com/questions/3157106/keydown-event-how-to-easily-know-if-the-key-pressed-is-numeric and also it might be a good idea to check this in KeyUp rather than KeyPress ... – vidriduch Sep 25 '14 at 15:26

2 Answers2

3

Yes.

Note you probably want IsDigit(char) rather than IsNumber(char), as discussed in Difference between Char.IsDigit() and Char.IsNumber() in C#.

public void Form_Load(object sender, EventArgs e)
{
    txtsample1.KeyPress += ValidateKeyPress;
    txtsample2.KeyPress += ValidateKeyPress;
}

private void ValidateKeyPress(object sender, KeyPressEventArgs e)
{
    // sender is the textbox the keypress happened in
    if (!Char.IsDigit(e.KeyChar)) //Make sure the entered key is a number (0-9)
    {
        // Tell the text box that the key press event was handled, do not process it
        e.Handled = true;
    }
}
Community
  • 1
  • 1
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
1

Sure, you can even register the same event on all your text boxes and process them all through one.

    void txt_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsNumber(e.KeyChar)) //Make sure the entered key is a number
            e.Handled = true; //Tells the text box that the key press event was handled, do not process it
    }
Jeffrey Wieder
  • 2,336
  • 1
  • 14
  • 12