C# 控件只能输入数字和小数点数字还必须是能转换成浮点类型
的。可以通过以下代码实现:
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 (e.KeyChar != '.' && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
在文本框的 KeyPress 事件中判断输入的字符是否为数字或小数点,如果不是则将 e.Handled 设为 true,表示该事件已经处理过了,不再继续传递。同时,还需要判断小数点只能输入一个,数字必须是能转换成浮点类型的。
原文地址: https://www.cveoy.top/t/topic/b77s 著作权归作者所有。请勿转载和采集!