.NET Programming With Me

VB.NET: How to generate Row Numbers in a column in DataGridView?

While filtering or loading data into the DataGridView, we don't have either sno or any row number from the query or the datasource and we want to view the row number to locate the data or to represent the particular row or to view in a regular format.


To get rid of the above problem I did some google and then get to know the event on which the increment can be done for DataGridView and then solved as below


The following code generates a serial number in a separate column in DataGridView:


Private Sub DataGridView1_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
        If e.RowIndex >= 0 Then
            Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = e.RowIndex + 1
        End If
    End Sub

VB.NET: How to get index of a column of a DataGridView?


Private Function GetColumnIndex(ByVal headerText)
        Dim columnIndex As Integer = 0


        For index As Integer = 0 To Me.DataGridView1.Columns.Count - 1


            If LCase(Me.DataGridView1.Columns(index).HeaderText) = LCase(headerText) Then
                 columnIndex  = index
                Exit For
            End If


        Next


        Return columnIndex 
    End Function