Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Put text in the Row Header of a DataGrid

How-to

Put text in the Row Header of a DataGrid

by  jebenson  Posted    (Edited  )
This code puts text in the row headers of a datagrid, like the line numbers in Excel.

'declare this global to the form
Dim point0-0 As Point

Then, in the DataGrid's Paint event handler:

Private Sub DataGrid1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGrid1.Paint
Dim row As Integer
Dim yChange As Integer
Dim y As Integer
Dim RowText As String
Dim hti As DataGrid.HitTestInfo

'this Static boolean keeps this Paint code from
'executing when the form is first loaded.

Static FirstLoad As Boolean = True


If Not FirstLoad Then
Try

'get the row that is currently displayed at top
hti = DataGrid1.HitTest(point0-0)

row = hti.Row

yChange = DataGrid1.GetCellBounds(row, 0).Height + 1
y = DataGrid1.GetCellBounds(row, 0).Top + 2


While (y <= DataGrid1.Height - yChange And row < ds.Tables("TableName").Rows.Count)
RowText = (row + 1).ToString
e.Graphics.DrawString(RowText, DataGrid1.Font, New SolidBrush(Color.Black), 12, y)
y += yChange
row += 1
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try



Else
FirstLoad = False
End If
End Sub


Finally, in the code where you populate your datagrid:

DataGrid1.DataSource = ds.Tables("TableName")

point0-0 = New Point(DataGrid1.GetCellBounds(0, 0).X + 4, DataGrid1.GetCellBounds(0, 0).Y + 4)

DataGrid1.TableStyles.Clear()

Dim ts As DataGridTableStyle

ts = New DataGridTableStyle

ts.MappingName = "TableName"

DataGrid1.TableStyles.Add(ts)

'this is to make sure that the rowheader column is wide
'enough to display the row numbers without
'them "bleeding" into the first column of data
'play with this a little to set it where you want

DataGrid1.TableStyles(0).RowHeaderWidth = 75
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top