Finding the Active datagridview in

bhlabelle used Ask the Experts™
Well I had a solution, but I want to reduce how much coding I do ('cause I'm no good at coding).
Basically I have a windows applicaton with a bunch of forms, and on each form is a tab control, and on each tab control is a bunch tabs all with different datagridviews, and the number keeps growing!

I found some code that nicely prints the datagridviews, and I wanted to be able to set "DataGridView1" (which is declared as "Private DataGridView1 As DataGridView") with the current datagridview the user is on.  

From the question I previously asked, I was able to get the name of the SelectedTab from the TabControl, which is the active control (the datagridview that is on the SelectedTab is NOT the active control as was suggested in the related question).  Then I have an "if" statement to set "DataGridView1":

Dim MyActiveTab As String = TabControl1.SelectedTab.Name
If MyActiveTab = "TabPage1" Then
            DataGridView1 = PartnershipsDataGridView
ElseIf MyActiveTab = "TabPage2" Then
            DataGridView1 = PartnersDataGridView
ElseIf MyActiveTab = "TabPage3" Then
etc, etc. and so on.

I do this because I know the name of the datagridview on each tab page.  Problem is I don't want to do this for every datagridview I add on every form ('cause I'm adding them all the time).  Any help/thoughts would be much appreciated.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2008

Is there a one-to-one relationship between TabPage and DataGridView (one DataGridView per tab)?


Yes, one DataGridView per TabPage
Most Valuable Expert 2012
Top Expert 2008
You should be able to loop through the controls for the current tab page, and get a reference to the DataGridView on the tab.

Private m_currentDataGridView As DataGridView

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

        ' Loop through all the controls on the current TabPage, looking for a DataGridView
        For Each ctl As Control In Me.TabControl1.SelectedTab.Controls
            If TypeOf ctl Is DataGridView Then
                m_currentDataGridView = ctl
                Exit For
            End If
    End Sub

Open in new window


Now I am (more)Learned..thanks for your quick response!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial