Friday, August 17, 2012

Display row number in WinForms DataGridView

In WinForms Applications, to display the row number in the row header, we could use the RowPostPaint event of DataGridView control.

Suppose grid is named as dgvUserDetails


this.dgvUserDetails.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgvUserDetails_RowPostPaint);

private void dgvUserDetails_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        using (SolidBrush b = new SolidBrush(dgvUserDetails.RowHeadersDefaultCellStyle.ForeColor))
              e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);

Don’t try to manipulate the Code part much because the X and Y are calculated co-ordinates in the row header area or you can customizse test it yourself to see the various results.