DataGridView本身沒有行號,所以要想得到行號,需要對第一列進行重繪。我們可以在rowspostpaint事件中增加處理代碼。
''' <summary>
''' 給GridView添加行號
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub DataGridView1_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles gridOrder.RowPostPaint
GridNO.NO(DataGridView1, e)
End Sub
Public Class GridNO
Public Shared Sub NO(ByVal dv As DataGridView, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs)
'在列前面加上行號
'在DataGridView的RowPostPaint事件中這樣調用:GridNo.NO(datagridview1,e)
Dim Color As Color = dv.RowHeadersDefaultCellStyle.ForeColor
If dv.Rows(e.RowIndex).Selected Then
Color = dv.RowHeadersDefaultCellStyle.SelectionForeColor
Else
Color = dv.RowHeadersDefaultCellStyle.ForeColor
End If
Dim b As SolidBrush = New SolidBrush(Color)
If e.RowIndex < 9 Then
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 22, e.RowBounds.Location.Y + 6)
ElseIf e.RowIndex < 99 Then
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 19, e.RowBounds.Location.Y + 6)
ElseIf e.RowIndex < 999 Then
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 16, e.RowBounds.Location.Y + 6)
ElseIf e.RowIndex < 9999 Then
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 13, e.RowBounds.Location.Y + 6)
Else
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 6)
End If
b.Dispose()
End Sub
End Class