您可以自己绘制行标题:
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;
}
}
我让数字向右对齐,并垂直居中."\u00a0"
是一个不间断的空格,它使行号与行标题单元格的右边缘保持最小距离.
我试了g.DrawString
和TextRenderer.DrawText
.后者使文本看起来与网格的其余部分更一致,并绘制出更清晰的文本.