vb.netvisual-studio-2013browsertabcontroltab-ordering

Vb.net How to programically select the last tab in a tabcontrol


I am making a Web Browser that has a TabControl and I can everything to work but when I click New Tab Button it creates a new tab with a web browser in it but I have to manually select that new tab to change the address. I want it so that when I click New Tab it redirects me automatically to the new tab not the current tab I was on. I have looked at "SelectedIndex" but that doesn't seem the best way to change the selected tab.

In Summmary When I click New Tab it...

  1. Creates a new tab at the END of the tab control with the url set to about:blank
  2. Doesn't change the selected tab to the "newly created tab"

Here is the code of the New Tab button

Private Sub btn_NewTab_Click(sender As Object, e As EventArgs) Handles btn_NewTab.Click
    AddTab("about:blank", TabControl1) 
End Sub

The AddTab Sub code is below

Public Sub AddTab(ByRef URL As String, ByRef TabControl As TabControl)
    Dim NewBrowser As New CustomBrowser
    Dim NewTab As New TabPage
    NewBrowser.Tag = NewTab
    NewTab.Tag = NewBrowser
    TabControl.TabPages.Add(NewTab)
    NewTab.Controls.Add(NewBrowser)
    NewBrowser.Dock = DockStyle.Fill
    NewBrowser.Navigate(URL)

End Sub

If you need to look at more of the code then he is a link to all of the code behind the web browser Full Code

Update: I Have tried adding

TabControl.SelectedIndex = TabControl.TabPages.Count - 1

to the AddTab sub and I get an error that highlights

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged Dim WB As CustomBrowser = Me.TabControl1.SelectedTab.Tag Me.cbURL.Text = WB.Url.ToString

End Sub

Solution

  • I don't wknow what was wrong with TabControl.SelectedIndex=TabControl.TabPages.Count-1, but you could also use TabControl.SelectTab:

    Public Sub AddTab(ByRef URL As String, ByRef TabControl As TabControl)
        Dim NewBrowser As New CustomBrowser
        Dim NewTab As New TabPage
        NewBrowser.Tag = NewTab
        NewTab.Tag = NewBrowser
        TabControl.TabPages.Add(NewTab)
        NewTab.Controls.Add(NewBrowser)
        NewBrowser.Dock = DockStyle.Fill
        NewBrowser.Navigate(URL)
    
        TabControl.SelectTab(NewTab)
    End Sub