Search Header Row and Go To The Specific Column That's Found

176 views Asked by At

So the following code grabs the header row and populates each field in a combobox.

I then want to select a field name from the combobox and go to that column in the datagridview, is that possible?

    Dim c As Integer
    For cn = 0 To DataGridView1.Columns.Count - 1
        c = c + cn
        'Debug.Print(cn)
        'Debug.Print(DataGridView1.Columns(cn).Name)
        ComboBox1.Items.Add(DataGridView1.Columns(cn).Name)
    Next cn
1

There are 1 answers

1
Ňɏssa Pøngjǣrdenlarp On BEST ANSWER

You'd want to check that the DGV has data and perhaps that there is a CurrentRow:

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, 
        e As EventArgs) Handles ComboBox1.SelectedIndexChanged

    ' ToDo: check that the selectedIndex is valid vs dgv.Columns.Count

    If dgv1.CurrentRow IsNot Nothing Then
        dgv1.CurrentCell = dgv1.CurrentRow.Cells(ComboBox1.SelectedIndex)
    Else
        dgv1.CurrentCell = dgv1.Rows(0).Cells(ComboBox1.SelectedIndex)
    End If

End Sub