如果想在DataGridView控件中自动添加行号,您可以在DataGridView控件CellPainting事件中添加相关代码。以下就是相关代码:
Private Sub DataGridView1_CellPainting(ByVal sender As Object,ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
'判断条件是:满足行数索引号要大于或等于0 and 列数的索引号时小于0If e.ColumnIndex < 0 And e.RowIndex >= 0 Then
e.Paint(e.ClipBounds,DataGridViewPaintParts.All)
Dim indexrect As Drawing.Rectangle = e.CellBounds
'定义显示的行号的坐标
indexrect.Inflate(-2,-2)
'绘画字符串的值
TextRenderer.DrawText(e.Graphics,(e.RowIndex + 1).ToString(),e.CellStyle.Font,indexrect,e.CellStyle.ForeColor,TextFormatFlags.Right)
e.Handled = True
End If
End Sub