Is it possible to show row number in the row header of a DataGridView
?
I'm trying with this code, but it doesn't work:
private void setRowNumber(DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.Rows)
{
row.HeaderCell.Value = row.Index + 1;
}
}
Do I have to set some DataGridView
property?
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);
}