C# WinForms 控件限制输入:仅允许输入数字和字母(小写自动转大写)
您可以使用以下代码来实现:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// 只允许输入数字和小写字母
if (!char.IsDigit(e.KeyChar) && !char.IsLower(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
else if (char.IsLower(e.KeyChar)) // 如果是小写字母,则转换成大写
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
}
在此代码中,我们使用 KeyPress 事件来限制输入内容。如果输入的字符不是数字或小写字母,则将 Handled 属性设置为 true,表示不允许输入该字符。如果输入的是小写字母,则将其转换成大写字母。
原文地址: https://www.cveoy.top/t/topic/jFGY 著作权归作者所有。请勿转载和采集!