Search code examples
c#winformsuser-controls

Set focus to control after datagridview selected index change


I am struggling with this issue for a long time now.

I have a user control in a tab page which contains:

  1. datagridview
  2. tablelayout with label, textbox and button controls which are set based on the row selected in the datagridview

Now the catch is that the focus must also change to a control within the tablelayout: If the selected item has state 'foo' , control 'foobar' must have the focus, but if the selected item has state 'foofoo', control 'foofoobar' must have the focus.

I handle this by using the SelectionChanged event.

This all works fine, if I manually click the selected item. When the control is initially loaded and the first row is selected, the focus is not set correctly.

My guess is, this has to do with the taborder setter of the Control class which overrides my focus, but I cannot figure out which event triggers the taborder setter.

I tried :

  1. overriding OnLoad and OnLayout and call the same code as called in the SelectionChanged event
  2. overriding OnLoad and OnLayout and first set the 2nd row, after which I set the 1st row to trigger the SelectionChanged event

But nothing works.

Any ideas are most welcome.

private void ResultGridView_SelectionChanged(object sender, EventArgs e) {
        SelectInput();
}

private void SetInputFocus() {
    if (isValid) {
        foo.Focus();
    } 
   else {
        foofoo.Focus();
    }

Solution

  • Set the focus in the YourTabControl_Layout event as you do in your SelectionChanged event.

    You can also set focus initially on any control, even on a tabpage and tablelayout with the Form1_Load event.

        private void Form1_Load(object sender, EventArgs e)
        {
            ActiveControl = SomeControl;
        }
    
        private void YourTabControl_Layout(object sender, LayoutEventArgs e)
        {
            if (YourTabControl.SelectedIndex == 0)
                SomeControl.Focus();
        }