C#,WinForm DataGridView添加行号(序号)

首次发布:2024-04-03 16:38

效果图

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 + 14, e.CellBounds.Location.Y + 8);
        }
        e.Handled = true;
    }
}

本文来自www.luofenming.com