Hello again!

This is something that's been bugging me for a while. Say I have a dgv with several columns and rows of data. Many times while working with the grid, it's necessary to know the number of the column, but all you know is the column header name, or vice versa. Is there any internal command that will return these values, or is there at least a better solution to the problem than making a function that loops through every header name until you find the one you want? It just seems so inefficient.

Thanks!

I am not tottaly sure what you are asking, but this may help:

Dim x, y As Integer
        x = e.rowIndex
        y = e.columnIndex
        TextBox1.Text = DataGridView1.Item(i, j).Value

Gives the currently selected cell

Sorry if I wasn't clear.

If I were using that code, but I don't know the actual column number that contains the data I want to enter into the text box (it's not selected by the user, it's being used in code), but I did know the header text, what I might do is something like this ..

Private Function GetHeaderNumber(ByVal headertext)
        For colindex = 0 To frmMain.dgvMain.Columns.Count - 1
            If LCase(frmMain.dgvMain.Columns(colindex).HeaderText) = LCase(headertext) Then
                Return colindex
                Exit For
            End If
        Next
End Function

This just seems like a rather inefficient way to find out the number of a column based on its header text. A project I was working on last year had 30+ fields that were always changing and being modified. This kind of function was being called all over the place. In a database with a structure that never, or rarely changes, I'd just access the columns by the number.

In the end, that project was using linq queries for this sort of thing, but that seems like overkill for smaller projects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.