感謝@加布裏埃爾 - 佩雷斯和@Groo,好主意!在其他人需要的情況下,這裏是在Visual Studio 2012中測試的VB版本。 在我的情況下,我希望數字在行標題中顯示在右上角。
Private Sub MyDGV_RowPostPaint(sender As Object, _
e As DataGridViewRowPostPaintEventArgs) Handles MyDataGridView.RowPostPaint
' Automatically maintains a Row Header Index Number
' like the Excel row number, independent of sort order
Dim grid As DataGridView = CType(sender, DataGridView)
Dim rowIdx As String = (e.RowIndex + 1).ToString()
Dim rowFont As New System.Drawing.Font("Tahoma", 8.0!, _
System.Drawing.FontStyle.Bold, _
System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Dim centerFormat = New StringFormat()
centerFormat.Alignment = StringAlignment.Far
centerFormat.LineAlignment = StringAlignment.Near
Dim headerBounds As Rectangle = New Rectangle(_
e.RowBounds.Left, e.RowBounds.Top, _
grid.RowHeadersWidth, e.RowBounds.Height)
e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, _
headerBounds, centerFormat)
End Sub
您還可以得到默認字體,rowFont = grid.RowHeadersDefaultCellStyle.Font
,但它可能看起來不那麼好。以下屏幕截圖使用的是Tahoma字體。
![Example on windows 7](https://i.stack.imgur.com/v084W.png)
不確定每個人都會遇到這種情況:我無法在Form_Load()之前設置HeaderCell的值 - 即在窗體的CTOR中。 – 2016-06-17 18:24:45