Nate E.
Nate E.

Reputation: 134

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.

Upvotes: 5

Views: 27524

Answers (4)

FanManPro
FanManPro

Reputation: 1155

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.

Upvotes: 11

Nate E.
Nate E.

Reputation: 134

using this solution worked perfectly...

txtMiles.Select();

Upvotes: 0

It's old, but someone could need this.

Control.Focus() is bugged. If it's not working, try workaround:

this.SelectNextControl(_controlname, true, true, true, true);

Change function parameters so they will work with your control, and remember about TabStop = true property of your control.

Upvotes: 4

Marcel B
Marcel B

Reputation: 518

You already have your txtMiles focused after the clear-button click. As for the Startup, set txtMiles.Focus() in your load-method.

private void MilesToKilometers_Load(object sender, EventArgs e)
{
    txtMiles.Focus();
}

Upvotes: 2

Related Questions