winform程序在datagridview首列中增加序号
1.在datagridview的属性中找到RowHeaderVisible并将其属性值更改为True,即可在datagridview最左侧看到增加一列。
2.在form中添加代码
private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
3.在form.Designer.cs中增加
this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgv_RowPostPaint);
结果如图所示