How to add row numbers to DataGridView
Categories: DotNetBar for Windows Forms, How To
You can render row numbers for DataGridView and DataGridViewX by handling RowPostPaint event. Then you use following code:
C#:
void DataGridViewRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { DataGridView dg = (DataGridView)sender; // Current row record string rowNumber = (e.RowIndex + 1).ToString(); // Format row based on number of records displayed by using leading zeros while (rowNumber.Length < dg.RowCount.ToString().Length) rowNumber = "0" + rowNumber; // Position text SizeF size = e.Graphics.MeasureString(rowNumber, this.Font); if (dg.RowHeadersWidth < (int)(size.Width + 20)) dg.RowHeadersWidth = (int)(size.Width + 20); // Use default system text brush Brush b = SystemBrushes.ControlText; // Draw row number e.Graphics.DrawString(rowNumber, dg.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2)); }
VB:
Private Sub DataGridViewRowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs) Dim dg As DataGridView = DirectCast(sender, DataGridView) ' Current row record Dim rowNumber As String = (e.RowIndex + 1).ToString() ' Format row based on number of records displayed by using leading zeros While rowNumber.Length < dg.RowCount.ToString().Length rowNumber = "0" & rowNumber End While ' Position text Dim size As SizeF = e.Graphics.MeasureString(rowNumber, Me.Font) If dg.RowHeadersWidth < CInt(size.Width + 20) Then dg.RowHeadersWidth = CInt(size.Width + 20) End If ' Use default system text brush Dim b As Brush = SystemBrushes.ControlText ' Draw row number e.Graphics.DrawString(rowNumber, dg.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2)) End Sub
Related posts: