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.
TonysieuAsked:
Who is Participating?
 
kemi67Commented:
0
 
CodeCruiserCommented:
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

0
 
Éric MoreauSenior .Net ConsultantCommented:
0
 
crafuseCommented:
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
0
 
TonysieuAuthor Commented:
Deselecting event worked just perfectly. Thanks very much.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.