Reputation: 2419
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
}
Upvotes: 0
Views: 2352
Reputation: 16609
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;
}
}
Upvotes: 3
Reputation: 2376
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
}
Upvotes: 1