winform datagridview 添加行号。

时间:2021-04-29 13:22:42

private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
  

private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var dgv = (DataGridView)sender;
if (dgv.RowHeadersVisible)
{
Rectangle rect = new Rectangle(e.RowBounds.Left, e.RowBounds.Top,
dgv.RowHeadersWidth, e.RowBounds.Height);
rect.Inflate(-2, -2);
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.InheritedRowStyle.Font,
rect, e.InheritedRowStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter
);

}
}

}