如何在 C# 中编写用于检查文本框浮点数的按键功能的通用函数?

How to write common function for keypress function check for floating number of a textbox in C#?

我想为 2 个以上的文本框调用一个通用函数,以便按键检查是否只有浮点数可以接受输入。

这是我的示例代码:它仅适用于单个文本框 (tbL1Distance)。但我希望它作为一个普通的文本框控件。

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;
        }
}

提前致谢。

您可以简单地创建自己的控件,继承 TextBox,在其中覆盖 OnKeyPress 方法。

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);
    }
}

完成后,转到 Build 菜单并按 Build <your project name here>,现在可以在工具箱顶部找到您的控件。现在只需将每个普通 TextBox 替换为您自己的

如果您根本不想在验证失败时触发 KeyPress 事件,您可以在两个 if 语句中添加 return;