C# WinForms 文本框限制输入数字和小数点 - 代码示例
通过以下代码实现,在 C# WinForms 中限制文本框只能输入数字和小数点,并且确保输入的数字能够转换为浮点类型:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// 只允许一个小数点
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
// 数字必须能转换成浮点类型
if (char.IsDigit(e.KeyChar) && !float.TryParse((sender as TextBox).Text + e.KeyChar, out _))
{
e.Handled = true;
}
}
在文本框的 KeyPress 事件中,判断输入的字符是否为数字或小数点,如果不是,则将 e.Handled 属性设置为 true,表示不允许输入。同时,判断小数点是否已经存在,如果存在,则也不允许输入。最后,判断输入的数字是否能转换成浮点类型,如果不能,则也不允许输入。
原文地址: https://www.cveoy.top/t/topic/jFGt 著作权归作者所有。请勿转载和采集!