可以通过以下方式实现:

  1. 在控件的 'KeyPress' 事件中判断输入的字符是否为数字或小数点,如果不是则取消输入。

  2. 在控件的 'TextChanged' 事件中判断输入的文本是否能转换为浮点类型,如果不能则清空控件的文本。

示例代码:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != (char)Keys.Back)
    {
        e.Handled = true;
    }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (!float.TryParse(textBox1.Text, out float value))
    {
        textBox1.Text = "";
    }
}
C# WinForms 控件限制输入数字和小数点

原文地址: https://www.cveoy.top/t/topic/jFGr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录