winform datagridview 添加行号。
先上图。
代码如下:
View Code
1 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
2 {
3 var dgv = (DataGridView)sender;
4 if (dgv.RowHeadersVisible)
5 {
6 Rectangle rect = new Rectangle(e.RowBounds.Left, e.RowBounds.Top,
7 dgv.RowHeadersWidth, e.RowBounds.Height);
8 rect.Inflate(-2, -2);
9 TextRenderer.DrawText(e.Graphics,
10 (e.RowIndex + 1).ToString(),
11 e.InheritedRowStyle.Font,
12 rect, e.InheritedRowStyle.ForeColor,
13 TextFormatFlags.Right | TextFormatFlags.VerticalCenter
14 );
15
16 }
17 }
2 {
3 var dgv = (DataGridView)sender;
4 if (dgv.RowHeadersVisible)
5 {
6 Rectangle rect = new Rectangle(e.RowBounds.Left, e.RowBounds.Top,
7 dgv.RowHeadersWidth, e.RowBounds.Height);
8 rect.Inflate(-2, -2);
9 TextRenderer.DrawText(e.Graphics,
10 (e.RowIndex + 1).ToString(),
11 e.InheritedRowStyle.Font,
12 rect, e.InheritedRowStyle.ForeColor,
13 TextFormatFlags.Right | TextFormatFlags.VerticalCenter
14 );
15
16 }
17 }