问题
I want to call a common function for more than 2 textboxes so that keypress can check that only floating point number can take a input.
This is my sample code: this work only for a single textbox (tbL1Distance). But I want it as a common textbox control.
private void tbL1Distance_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == 46 && tbL1Distance.Text.IndexOf('.') != -1)
{
e.Handled = true;
return;
}
if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
{
e.Handled = true;
}
}
Thanks in advance.
回答1:
You can simply create your own control, inheriting the TextBox, where you override the OnKeyPress method.
public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == 46 && this.Text.IndexOf('.') != -1) //Replaced 'tbL1Distance' with 'this' to refer to the current TextBox.
{
e.Handled = true;
}
else if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}
When done, go to the Build menu and press Build <your project name here>, and your control can now be found on the top of your Tool Box. Now just replace every normal TextBox with your own.
If you don't want the KeyPress event to be fired at all if your validation fails, you can just add return; in both if-statements.
来源:https://stackoverflow.com/questions/36383670/how-to-write-common-function-for-keypress-function-check-for-floating-number-of