我有一个只包含数字的文本框。检查在离开事件中进行。如果文本框包含字符而不是数字,则会提示用户检查其输入并再次尝试,同时保持对文本框的关注。
问题在于,如果用户按下取消,文本框仍然保持聚焦状态,并且无法单击表单中的其他位置。如果他删除文本框的内容,也会发生同样的情况。我究竟做错了什么?非常感谢一些帮助!提前谢谢!
private void whateverTextBox_Leave(object sender, EventArgs e)
{
//checks to see if the text box is blank or not. if not blank the if happens
if (whateverTextbox.Text != String.Empty)
{
double parsedValue;
//checks to see if the value inside the checkbox is a number or not, if not a number the if happens
if (!double.TryParse(whateverTextbox.Text, out parsedValue))
{
DialogResult reply = MessageBox.Show("Numbers only!" + "\n" + "Press ok to try again or Cancel to abort the operation", "Warning!", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
//if the user presses ok, textbox gets erased, gets to try again
if (reply == DialogResult.OK)
{
whateverTextbox.Clear();
whateverTextbox.Focus();
}
//if the user presses cancel, the input operation will be aborted
else if (reply == DialogResult.Cancel)
{
whateverTextbox.Clear();
//whateverTextbox.Text = String.Empty;
//nextTextBox.Focus();
}
}
}
}
答案 0 :(得分:1)
为什么不做这样的事情:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
MessageBox.Show("Numbers only!" + "\n" + "Press ok to try again or Cancel to abort the operation", "Warning!");
}
}