JYelton
JYelton

Reputation: 36546

How do I detect a change of tab page in TabControl prior to SelectedIndexChanged event?

I currently determine what page of a tabcontrol was clicked on via the SelectedIndexChanged event.

I would like to detect before the selected index actually changes, for validation purposes. For example, a user clicks a tab page other than the one they are viewing. A dialog is presented if form data is unsaved and asks if it's ok to proceed. If the user clicks no, the user should remain on the current tab.

Currently I have to remember the previous tab page and switch back to it after an answer of 'no.'

I considered MouseDown (and the assorted calculation logic), but I doubt that's the best way.

Upvotes: 39

Views: 79842

Answers (3)

mattpm
mattpm

Reputation: 1390

I've actually tried all of the events including the suggestions here and none of the mentioned events occur at the right time to actually trap moving from the tab.

Even the tab page validation event fires when entering the tab rather than leaving it - either that or there's something peculiar going on with my machine or .NET 4. On the other hand, in .NET 4 there is the Deselecting event which fires at the right time for my purposes.

    private void tab_Deselecting(object sender, TabControlCancelEventArgs e)
    {

    }

Upvotes: 10

Cheng Chen
Cheng Chen

Reputation: 43531

Add such an event to the tabControl when form_load:

tabControl1.Selecting += new TabControlCancelEventHandler(tabControl1_Selecting);

void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    TabPage current = (sender as TabControl).SelectedTab;

    // Validate the current page. To cancel the select, use:
    e.Cancel = true;
}

Upvotes: 51

Chris Schmich
Chris Schmich

Reputation: 29524

The TabControl has a collection of TabPages, each of which you can enforce validation on, e.g.:

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();

        foreach (var page in _tabControl.TabPages.Cast<TabPage>())
        {
            page.CausesValidation = true;
            page.Validating += new CancelEventHandler(OnTabPageValidating);
        }
    }

    void OnTabPageValidating(object sender, CancelEventArgs e)
    {
        TabPage page = sender as TabPage;
        if (page == null)
            return;

        if (/* some validation fails */)
            e.Cancel = true;
    }
}

Upvotes: 8

Related Questions