WinForm DataGridView中显示序号
效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/c75be2a533884210996a7011aeb46c52.png)
代码
public Basic_configuration()
{
InitializeComponent();
#region 更改表格颜色
#endregion
#region 表格居左
dataGridView_basic.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
#endregion
#region 表格行号
dataGridView_basic.RowPostPaint += DataGridView_RowPostPaint;
dataGridView_basic.RowHeadersVisible = true;
dataGridView_basic.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
dataGridView_basic.RowHeadersWidth = Properties.Settings.Default.RowHeadersWidth_Start + Properties.Settings.Default.RowHeadersWidth_Add * 2;
#endregion
}
private void DataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataGridView datagridview = sender as DataGridView;
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
datagridview.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
datagridview.RowHeadersDefaultCellStyle.Font,
rectangle,
datagridview.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}