Link to home
Start Free TrialLog in
Avatar of Tonysieu
Tonysieu

asked on

How to intercept SelectedIndexChanged event in a TabControl?

Hi there,

I have a TabControl form. I need to make sure users have saved the data before changing tab or closing the form.

Whenever they try to close the form or change tab they get a "Save changes?" YesNoCancel message box.

Yes = save and close (or change tab)
No = don't save and close(or change tab)
Cancel = don't save and don't close (or change tab), leave it be

Yes and No options are no problem at all. My problem is with the Cancel option.

When user tries to close a form I use the following code in form_closing event and it works perfectly:

If msgResult = MsgBoxResult.Cancel Then
     e.Cancel = True
End If

But when user tries to change tabs, I cannot stop the SelectedIndexChanged event. It happens regardless.

How can I stop this event and stay on the tab? I could change the selectedIndex back to the original tab but that would remove the changes user have made. I simply want to intercept the SelectedIndexChanged event and close the message box.

Your help would be appreciated.
ASKER CERTIFIED SOLUTION
Avatar of Michele Segato
Michele Segato
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can use the Selecting event as well which has the e.cancel option and is intended for this purpose

Occurs before a tab is selected, enabling a handler to cancel the tab change.

http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.selecting.aspx

not sure i understand the question. after they try and change tabs, and select 'Cancel' (this fires AFTER the tab control selected index change, correct?), you want them to remain on the original tab, and all data values there remain inert, unsaved and unchanged? so all current values remain? i can play with this a bit tomorrow, seems pretty straightforward, let me know if you need me to (those above me are about as good as it gets, so maybe look at their answers first...)...

this is a straightforward event handler i use with one of my tab controls (tbcMultiPlayer). :

Private Sub tbcMultiPlayer_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbcMultiPlayer.SelectedIndexChanged
        Try
            Dim showThisTAB As Integer = Me.tbcMultiPlayer.SelectedIndex
            Select Case showThisTAB
                Case 0  'TAB1
                    '//do what you want here...
                Case 1  'TAB2
                    '//do what you want here...
             End Select
        Catch ex As Exception
            MsgBox("Sub ->tbcMultiPlayer_SelectedIndexChanged " & ex.ToString)
        End Try
    End Sub
Avatar of Tonysieu
Tonysieu

ASKER

Deselecting event worked just perfectly. Thanks very much.