C#,WinForm DataGridView添加行号

效果图

image.png

核心代码

//注册事件 this.dataGridView1.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == -1)
    {
        e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
        using (Brush brush = new SolidBrush(e.CellStyle.ForeColor))
        {
            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.CellStyle.Font, brush, e.CellBounds.Location.X + 10, e.CellBounds.Location.Y + 4);
        }
        e.Handled = true;
    }
}

本文来自www.luofenming.com