在 C# Winform 中,可以使用 KeyPress 事件来限制用户输入的字符。在该事件中,可以通过判断输入的字符是否为数字或小数点,以及是否能转换成浮点数来进行限制。以下是一个示例代码:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // 如果输入的字符不是数字、小数点、退格键或删除键,则取消输入
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Delete)
    {
        e.Handled = true;
        return;
    }

    // 如果输入的字符是小数点,并且已经存在一个小数点,则取消输入
    if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') >= 0)
    {
        e.Handled = true;
        return;
    }

    // 如果输入的字符是数字或小数点,则判断是否能转换成浮点类型
    if (char.IsDigit(e.KeyChar) || e.KeyChar == '.')
    {
        string text = (sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.KeyChar.ToString());
        float value;
        if (!float.TryParse(text, out value))
        {
            e.Handled = true;
            return;
        }
    }
}

需要注意的是,上述代码中使用了 KeyChar 属性来获取用户输入的字符,但是在 WPF 中是没有 KeyChar 属性的。如果需要在 WPF 中实现类似的功能,可以使用 PreviewTextInput 事件来代替 KeyPress 事件。

C# Winform 限制 TextBox 输入:仅允许数字和小数点,并校验浮点数

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

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