Why doesn't this event fire?

Add a form. Add a tabcontrol to the form. Add some tabs to the tabcontrol. Add the following code to the form.

Why doesn't the TabControl1.SelectedIndexChanged event fire when I *set* the selectedIndex  How do I make it so that the event *does* fire if the value is set through code


Public Class Form1
    Inherits System.Windows.Forms.Form

' Windows forms designer code removed

    Private _iLastIndex As Short

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SelectTab(TabControl1, 0)
    End Sub

    Private Sub SelectTab(ByVal ctrl As TabControl, ByVal iTab As Short)
        ctrl.selectedIndex = iTab
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        Try
            If _iLastIndex <> TabControl1.SelectedIndex Then
                MsgBox(TabControl1.SelectedTab.Name)
                _iLastIndex = TabControl1.SelectedIndex
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

End Class


Answer this question

Why doesn't this event fire?

  • Aaron Marten - MSFT

    Setting _iLastIndex = -1 initially will cause your code to fire.  You'll just get the error message the first time before the form is drawn.  Setting TabControl1.SelectedIndex = -1 will give the same result.

    The event fires everytime, it's just that after the form is drawn the first tabpage (page 0) is set as selected.

  • Doom Gaze

    Weel, it doesn't fire for me. So I'll scrap that method and look for another solution.
  • Ciprian Gerea MSFT

    It does.

    _iLastIndex is initialized to 0, meaning "_iLastIndex <> TabControl1.SelectedIndex" returns false.

    Try calling SelectTab(TabControl1, 1) and you'll see that the event does fire.

  • Bo Yu

    I've tried setting _iLastIndex to -1 beforehand - it still doesn't go through.

    how do I make it fire <u>on form load</u> for tab index "0" 

  • Why doesn't this event fire?