tags:

views:

110

answers:

2

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, I'd like to 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.

(This is in .NET C# 3.5)

+2  A: 

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;
    }
}
Chris Schmich
I've used Validation events before and considered it again, but for the purposes of this application, it's more than I need. Thanks however.
JYelton
+2  A: 

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;
    }
Danny Chen
Precisely the event I was looking for (and apparently not seeing). Thanks.
JYelton