C# WinForms TextBox 限制输入为数字和小数点的有效浮点数

本文将介绍如何在 C# WinForms 中的 TextBox 控件中限制用户输入,只允许输入数字、小数点和负号,并且输入的值必须能够转换为有效的浮点数。

以下是一个实现该功能的示例代码:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // 允许输入数字、小数点、删除键和退格键
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
    {
        e.Handled = true;
    }

    // 允许输入负号,但只能在第一位输入
    if ((e.KeyChar == '-') && ((sender as TextBox).Text.IndexOf('-') > -1 || (sender as TextBox).SelectionStart != 0))
    {
        e.Handled = true;
    }

    // 允许输入小数点,但只能输入一次
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }

    // 允许输入数字和小数点,但数字必须能转换成浮点类型
    if (char.IsDigit(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == '-')
    {
        // 获取文本框中的值
        string text = (sender as TextBox).Text;

        // 在光标位置插入当前输入的字符
        text = text.Substring(0, (sender as TextBox).SelectionStart) + e.KeyChar + text.Substring((sender as TextBox).SelectionStart);

        // 判断是否能转换成浮点类型
        float value;
        if (!float.TryParse(text, out value))
        {
            e.Handled = true;
        }
    }
}

在该代码中,我们通过 KeyPress 事件来监听文本框的键盘输入。

首先,我们允许输入数字、小数点、删除键和退格键,并且允许输入负号,但只能在第一位输入。

其次,我们允许输入小数点,但只能输入一次。

最后,我们允许输入数字和小数点,但数字必须能转换成浮点类型,如果不能转换,则禁止输入。

通过这种方法,我们可以有效地限制用户在 TextBox 中的输入,保证其输入的值是一个有效的浮点数。

C# WinForms TextBox 限制输入为数字和小数点的有效浮点数

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

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