Datagrid formatting

  • Thread starter Thread starter John Dann
  • Start date Start date
J

John Dann

I've got what seems to be a common problem with the DataGrid control -
I want to display a dataset one of whose columns (always the first
column) is a datetime column. But only the date displays not the time.

The dataset structure is only defined at runtime so I want to set the
format of just this one datetime column programmatically. Would anyone
be kind enough to tell me the simplest way of doing so. This is just a
detail, albeit an important one, in an urgent larger project and I'd
really rather not get diverted into reading up on all the intricacies
of the DataGrid - a control I don't normally need to use!

Thanks if anyone can help.
JGD
 
John,

I use a class with 1 shared method named Format to format a datagrid at
runtime with data from a datatable. The Format method formats any datetime
columns to display the date and time. You might be able to modify the code
for your needs.

Note that the code is compiled with Option Strict OFF, so you might need to
do some type casting if you compile with Option Strict ON.

Here is the code:

Public Class GridFormatter

Public Shared Sub Format(ByRef grd As DataGrid, ByRef dt As DataTable)

Dim ts As New DataGridTableStyle()
Dim tc As DataGridTextBoxColumn

Dim dc As DataColumn
For Each dc In dt.Columns
tc = New DataGridTextBoxColumn()
tc.MappingName = dc.ColumnName
tc.HeaderText = tc.MappingName

If dc.DataType Is GetType(System.DateTime) Then
tc.Format = "MM/dd/yyyy hh:mm:ss"
tc.Width = 125
End If

ts.GridColumnStyles.Add(tc)
Next

grd.TableStyles.Clear()
grd.TableStyles.Add(ts)

grd.DataSource = Nothing
grd.DataSource = dt

End Sub

End Class

Call the Format function like this:

GridFormatter.Format (myDataGrid, myDataTable)

Kerry Moorman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top