Monday, June 29, 2009

Display RowNumbers in datagridview

Namespace MyDataGridView
'''
''' display a datagrid with row numbers
'''

Class MyDataGridView
Inherits DataGridView
'''
''' draw the row number on the header cell, auto adjust the column width
''' to fit the row number
'''

'''
Protected Overloads Overrides Sub OnRowPostPaint(ByVal e As DataGridViewRowPostPaintEventArgs)
MyBase.OnRowPostPaint(e)

' get the row number in leading zero format,
' where the width of the number = the width of the maximum number
Dim RowNumWidth As Integer = Me.RowCount.ToString().Length
Dim RowNumber As New StringBuilder(RowNumWidth)
RowNumber.Append(e.RowIndex + 1)
While RowNumber.Length < RowNumWidth
RowNumber.Insert(0, " ")
End While

' get the size of the row number string
Dim Sz As SizeF = e.Graphics.MeasureString(RowNumber.ToString(), Me.Font)

' adjust the width of the column that contains the row header cells
If Me.RowHeadersWidth < CInt((Sz.Width + 20)) Then
Me.RowHeadersWidth = CInt((Sz.Width + 20))
End If

' draw the row number
e.Graphics.DrawString(RowNumber.ToString(), Me.Font, SystemBrushes.ControlText, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - Sz.Height) / 2))
End Sub
End Class
End Namespace

No comments:

Post a Comment