namco
namco

Reputation: 6348

how to unfocus datagridview in winform

I have some buttons, one textbox and a datagridview on a winform.
and i want when form show in the screen to put cursor on the textblock,
for this i use txtName.Focus().
But everytime when the from loads textbox doesn't focus, indeed dagaridview takes a focus on itself.
how to solve it.

Upvotes: 0

Views: 1893

Answers (4)

ImGreg
ImGreg

Reputation: 2993

You have to make sure that the page has been loaded before giving the textbox focus. Therefore, add an event for the Form's Load event.

You can do this on the designer, or in the code behind like so:

this.Load += new EventHandler(Form1_Load);

During the loading event, call Select on your textbox.

private void Form1_Load(object sender, EventArgs e){
    txt_Name.Select();
}

The Select command can choose how much of the text you select. For example, select the first letter starting a index 0 would be txt_Name.Select(0,0). More info at the MSDN.

Alternatively, you can use the tabindex property to 0 to ensure it gets focus first (as per ionden).

Upvotes: 0

   private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.TabStop = false;
            textBox1.TabIndex = 0;
        }

hope its help

Upvotes: 3

ionden
ionden

Reputation: 12786

You should set the TabIndex property of the controls in your form (your TextBox for example should have the lowest TabIndex so that when the form loads it will automatically have focus )

Upvotes: 3

Steve
Steve

Reputation: 216363

Simply change the tabindex property of your controls.
Pay attention to use directly the tabindex property, because, if you have controls contained in other controls (groupbox or panels) it could be misleading.
Use the menu View and the TabOrder tool.
Put your textbox first in the taborder. No need to code anything

Upvotes: 2

Related Questions