tags:

views:

67

answers:

2

Using TabControl.SelectTab("...") shows the tab but it also gives the tab focus. I would like to show a particular tab, but keep focus where it is.

I have data rows in a grid. Based on properties of the selected row, I show a different tab page to have a different UI layout. But when using arrow keys to scroll through rows, the focus switches to the selected tab -- which I don't want to happen.

Thanks.

A: 

I don't think there's a built-in function, but you can do in this way:

private bool skipSelectionChanged = false;

private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
    if (skipSelectionChanged)
        return;

    // supposing we decide tab[0] has to be selected...
    this.SelectTabWithoutFocus(this.tabControl1.TabPages[0]);
}

private void SelectTabWithoutFocus(TabPage tabPage)
{
    this.skipSelectionChanged = true;

    // "this" is the form in my case, so you get the current focused control
    // (ActiveControl), backup it, and re-set it after Tab activation

    var prevFocusedControl = this.ActiveControl;
    if (this.ActiveControl != null)
    {
        this.tabControl1.SelectedTab = tabPage;
        prevFocusedControl.Focus();
    }
    this.skipSelectionChanged = false;
}

Here, I backup the current focused control, select the desired tab, and finally set the focus to the original control.

Skipping boolean is necessary, because giving the focus to the grid you trigger SelectionChanged event again, causing infinite looping.

digEmAll
+2  A: 

You can try disabling the TabControl before setting the selected tab, then re-enabling it. This will prevent it from taking focus. I tested this on a tab control with a few controls on it, and didn't see any visual change, but you'll have to try it in your UI and see whether it's ok for you.

tabControl1.Enabled = false;
tabControl1.SelectTab("tabPage4");
tabControl1.Enabled = true;

To be safe, you could put the line to re-enable the TabControl in a finally block to make sure it doesn't get left disabled.

adrift
+1 Really smart !
digEmAll
This is nice idea and it works correctly, but the performance is not very good to enable/disable the control. The reason is that each of my tab pages has a lot of controls, so each one is disabled/enabled, which takes a lot of time and does not look great in UI.
TheSean
@TheSean, I don't know if there is another way to stop it from taking focus. I take it that taking the focus back from the tab control after the user selects a new row in the grid does not work for you?
adrift
I previously deleted my solution, because is a bit hacky/workaroundish but maybe faster than disable/enable the tabcontrol. I undeleted it if you wanna try ;)
digEmAll