C# 我想有一个文本框提醒用户,当他们输入错误的字符
这是我目前拥有的,我已经尝试扩展if语句,让一个MessageBox出现,并在keypress上提醒用户,但我没有任何运气。这里是我的作品,限制用户输入。在Windows窗体中C# 我想有一个文本框提醒用户,当他们输入错误的字符,c#,winforms,.net-core,C#,Winforms,.net Core,这是我目前拥有的,我已经尝试扩展if语句,让一个MessageBox出现,并在keypress上提醒用户,但我没有任何运气。这里是我的作品,限制用户输入。在Windows窗体中 private void PhoneText_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) {
private void PhoneText_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
例如,在else条件下,更改背景颜色:
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
PhoneText.BackColor = Color.White;
}
else
{
PhoneText.BackColor = Color.IndianRed;
}
将代码修改为:
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Incorrect Character!");
}
我通常只允许使用数字和小数:
Char chr = e.KeyChar;
if (!char.IsDigit(chr) && e.KeyChar!='.')
{
e.Handled = true;
MessageBox.Show("Please enter only numeric values.");
}
这不是一个问题的解决方案。好的,有了这个代码,当我输入数字时,它会变成红色,但当我按下字母键时,什么都没有发生。有什么想法吗?显然不会显示任何消息,因为代码中没有任何消息。您是否尝试显示MessageBox,如果是,您是否可以在此类呼叫中显示代码?@sswifty6:如果答案对您有帮助,您应该将其标记为答案。如果没有,您可以评论并告知此人错误,以便他能够帮助您。