Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell which tab you are moving from/to in a WinForms tab control?

I need to determine which tab the user is coming from, and going to, when they switch tabs, and possibly cancel the switch. I have tried the Deselecting, Deselected, Selecting, Selected events, and all of them show the e.TabPageIndex to be the same as the sender.SelectedIndex.

Is there an event, or property, that I can use so that I can determine both sides of this, or do I have to hack something together with caching it from one event and using that value in the new event.

I am trying to avoid handling the Deselecting/Deselected events and caching the value to use in the Selecting event. I already know I can do this, so I am asking if there is a cleaner way, without doing this.

I have tried in both C# and VB, with the same results (no surprise).

Thanks.

like image 608
Rick Mogstad Avatar asked Aug 24 '09 16:08

Rick Mogstad


1 Answers

It doesn't look like any one event argument will carry the details of both the previous and current tabs, so you'll need to handle a couple of events to keep track.

At a minimum, you'd need to use the Deselected event to store a reference to the previously-selected tab. You can always query the TabControl for its current tab. To stretch a little further, you can also handle the Selected event to track the current tab.

Option Strict On
Option Explicit On

Public Class Form1

    Private PreviousTab As TabPage
    Private CurrentTab As TabPage

    Private Sub TabControl1_Deselected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Deselected
        PreviousTab = e.TabPage
        Debug.WriteLine("Deselected: " + e.TabPage.Name)
    End Sub

    Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
        CurrentTab = e.TabPage
        Debug.WriteLine("Selected: " + e.TabPage.Name)
    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        If CurrentTab Is Nothing Then Return
        Debug.WriteLine(String.Format("Proposed change from {0} to {1}", CurrentTab.Name, e.TabPage.Name))
    End Sub

End Class
like image 78
STW Avatar answered Oct 22 '22 12:10

STW