The datagridview shows the data nicely, but I want to see numbers sequentially instead of pointers at the rows header.
As seen in the picture, there is an arrow in the header cell. I don't want like this, When I write the code below, the numbers only appear when the mouse hovers over them.
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
I want to see it directly in the line headings like in the image directly below
You can draw the row header yourself:
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
// Draw only if the cell is the row header: e.ColumnIndex == -1
// and the row is not the column header: e.RowIndex >= 0
if (e.ColumnIndex == -1 && e.RowIndex >= 0) {
bool isSelected = (e.State & DataGridViewElementStates.Selected) != 0;
e.PaintBackground(e.ClipBounds, isSelected);
var grid = (DataGridView)sender;
if (e.RowIndex == grid.CurrentRow.Index) {
e.PaintContent(e.ClipBounds); // Paints the selection arrow
}
var g = e.Graphics!;
TextRenderer.DrawText(g, $"{e.RowIndex + 1}\u00a0", grid.Font, e.CellBounds,
grid.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
e.Handled = true;
}
}
I made the number align to the right and centered vertically. "\u00a0"
is a non-breaking space that gives the row number a minimal distance to the right edge of the row header cell.
I tried g.DrawString
and TextRenderer.DrawText
. The latter one makes text look more consistent with the rest of the grid and draws a sharper text.