简体   繁体   中英

C#: How to cancel the focus of a previousely focused text box?

I have a textbox which should contain only numbers. The check is made in the Leave event. If the textbox contains characters and not numbers, it prompts the user to check their input and try again while remaining focused on the textbox.

The problem is that if the user presses cancel, the textbox still remains focused and can't click elsewhere in the form. The same happens if he deletes the contents of the textbox. What am I doing wrong? Would appreciate some help! Thanks in advance!

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();
                }
            }
        }
    }

Why not just do something like this:

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!");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM