Show row number in row header of a DataGridView
Thanks @Gabriel-Perez and @Groo, great idea! In case others want it, here's a version in VB tested in Visual Studio 2012. In my case I wanted the numbers to appear top right aligned in the Row Header.
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
You can also get the default font, rowFont = grid.RowHeadersDefaultCellStyle.Font
, but it might not look as good. The screenshot below is using the Tahoma font.
You can also draw the string dynamically inside the RowPostPaint
event:
private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
It seems that it doesn't turn it into a string. Try
row.HeaderCell.Value = String.Format("{0}", row.Index + 1);