Tag Archives: DataGridView

C# .Net

How to Elegantly Add Row Numbering for DataGridView Tables

There are a few ways to go about adding row numbering for your DataGridView’s, but you have to ensure you have added the code in, where ever you are adding a new row. If your inserting a row, then you have to go back and update all your numbering. With the option shown here, you need not worry about updating any row numbers when working with the DataGridView.

DGV_RowPostPaint_01

Once you add the event for the ‘RowPostPaint’, the code (function header outlined in red) just needs to be updated to reference the routine (function header outlined in green). I keep the numbering routine in its own block of code so that is can be reused by other DataGridView tables on the same form.

private void dgv_CompanySites_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
bg_DGV_RowPostPaint(sender, e);
}

private void bg_DGV_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
     var bgDGV = sender as DataGridView;
    var bgRowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat()
    {
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center,
        LineAlignment = StringAlignment.Center
    };   

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, bgDGV.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(bgRowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

When you load your DataGridView, the RowPostPaint event will be raised to perform row level painting, after all cell painting has occurred. This renders your row numbering nicely, and you do not have to add any additional code for numbering when adding data rows.

The following example shows the numbering where the numbers are low in range:

DGV_RowPostPaint_03

As your numbering gets higher up in range, the spacing remains nicely proportioned:

DGV_RowPostPaint_02