DataGridView添加ID列

列表行的头显示ID列
解决方案:
首先,将DataGridView中的属性RowHeadersVisible置为True
其次,在事件RowPostPaint中添加如下代码:

  private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
  {
        var dgv = sender as DataGridView;
        Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
            e.RowBounds.Location.Y,
            dgv.RowHeadersWidth - 4,
            e.RowBounds.Height);
        TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dgv.RowHeadersDefaultCellStyle.Font,
            rectangle,
            dgv.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  }

你可能感兴趣的:(小知识点)