Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# set focus on textbox

I'm trying to set the "txtMiles" textbox to focus after:

  1. The form opens
  2. When the "clear" button is clicked

I have tried using txtMiles.Focus(); but it doesn't seem to work for me.

CODE BEING USED ON THIS FORM

        private void btnConvert_Click(object sender, EventArgs e)
        {
            //assigns variable in memory.
            double txtMile = 0;
            double Results;

            try
            {
                // here is where the math happens.
                txtMile = double.Parse(txtMiles.Text);
                Results = txtMile * CONVERSION;
                lblResults.Text = Results.ToString("n2");
                txtMiles.Focus();
            }
                // if the user enters an incorrect value this test will alert them of such.
            catch
            {
                //MessageBox.Show (ex.ToString());
                MessageBox.Show("You entered an incorrect value");
                txtMiles.Focus();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //This empties all the fields on the form.
            txtMiles.Text = "";
            txtMiles.Focus();
            lblResults.Text = "";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
           // closes program
            this.Close();
        }
    }
}

Thanks in advance for the help.

like image 676
Nate E. Avatar asked Dec 07 '22 23:12

Nate E.


1 Answers

You should make sure your TabIndex is set and then instead of Focus(), try use Select(). See this MSDN link.

txtMiles.Select();

Also make sure there isn't a TabStop = true attribute set in the view file.

like image 162
FanManPro Avatar answered Dec 26 '22 21:12

FanManPro