How can I disable a tab inside a TabControl?

Is there a way to disable a tab in a TabControl?


Solution 1:

Cast your TabPage to a Control, then set the Enabled property to false.

((Control)this.tabPage).Enabled = false;

Therefore, the tabpage's header will still be enabled but its contents will be disabled.

Solution 2:

The TabPage class hides the Enabled property. That was intentional as there is an awkward UI design problem with it. The basic issue is that disabling the page does not also disable the tab. And if try to work around that by disabling the tab with the Selecting event then it does not work when the TabControl has only one page.

If these usability problems do not concern you then keep in mind that the property still works, it is merely hidden from IntelliSense. If the FUD is uncomfortable then you can simply do this:

public static void EnableTab(TabPage page, bool enable) {
    foreach (Control ctl in page.Controls) ctl.Enabled = enable;
}

Solution 3:

You can simply use:

tabPage.Enabled = false;

This property is not shown, but it works without any problems.

You can program the Selecting event on TabControler to make it impossible to change to a non-editable tab:

private void tabControler_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPageIndex < 0) return;
    e.Cancel = !e.TabPage.Enabled;
}

Solution 4:

You could register the "Selecting" event and cancel the navigation to the tab page:

private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPage == tabPage2)
        e.Cancel = true;
}

Another idea is to put all the controls on the tabpage in a Panel control and disable the panel! Smiley

You could also remove the tabpage from the tabControl1.TabPages collection. That would hide the tabpage.

Credits go to littleguru @ Channel 9.

Solution 5:

Presumably, you want to see the tab in the tab control, but you want it to be "disabled" (i.e., greyed, and unselectable). There is no built-in support for this, but you can override the drawing mechanism to give the desired effect.

An example of how to do this is provided here.

The magic is in this snippet from the presented source, and in the DisableTab_DrawItem method:

this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
this.tabControl1.DrawItem += new DrawItemEventHandler( DisableTab_DrawItem );