C# WinForms 控件限制输入数字和小数点并自动转为大写
C# WinForms 控件限制输入数字和小数点并自动转为大写
本教程将教你如何在 C# WinForms 应用程序中,限制文本框控件只允许输入数字和小数点,并将输入的小写字母自动转换为大写字母显示。
步骤:
- 限制输入: 在控件的
KeyPress事件中,限制输入只能为数字和小数点:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
}
}
- 转换大小写: 在控件的
TextChanged事件中,将小写字母转换成大写字母并显示:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.ToUpper();
}
完整代码:
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)
{
textBox1.Text = textBox1.Text.ToUpper();
}
注意:
- 将
textBox1替换为你的实际控件名称。 - 确保在控件的属性面板中,
TextChanged和KeyPress事件已绑定到相应的方法。
现在,你的文本框控件只能输入数字和小数点,且输入的任何小写字母都将自动转换为大写字母显示。
原文地址: https://www.cveoy.top/t/topic/jFGT 著作权归作者所有。请勿转载和采集!