JYelton JYelton - 1 year ago 150
C# Question

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


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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download