C# – How to detect a change of tab page in TabControl prior to SelectedIndexChanged event

.net-3.5cwinforms

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.

Best Answer

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;
}
Related Topic