GridView sorting

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a vb.net 2.0 app that is loading a GridView with a DataSource that is
returned from a function.

The definitions in the function are:

Dim ReportDS As DataSet = New DataSet
Dim ReportTable As System.Data.DataTable = New
System.Data.DataTable("SendTo")

The ReportTable is populated row by row by data gotten back from the
Exchange server.

I then set ReportDS.Tables.Add(ReportTable) and return ReportDS

I then set GridView.DataSource = ReportDS()

This displays exactly as I want it to.

The question is how do I enable sorting on the GridView where it will
actually sort? Setting AllowSorting="True" causes a post back, but no
sorting occurs. What is the optimal way to be able to enable sorting here?

Thanks.
 
Hi Gerhard,
When you set the datasource of the GridView to a dataset or a datatable,
actually this is what happens.
Considering your case : if you write this

Dim ReportTable As System.Data.DataTable = New System.Data.DataTable
"SendTo")
GridView.DataSource = ReportTable

this happens
GridView.DataSource = ReportTable.DefaultView

The datasource is actually set to a DataView not a table or DataSet. Paging
and sorting is done on DataView.

To accomplish what you want you can do this :
DataView dv = new DataView(ReportTable);
dv.Sort = " Name ASC"; or dv.Sort= "Country DESC"; etc
GridView.DataSource = dv;

I hope this helps. In case of any difficult feel free to get back.
 
Thanks. This helped alot!

One last question. Everything is working fine on this, except for the sort
on one column. This column is populate with a Date value as follows:

ReportTable.Columns.Add("Date")

Dim dateReceived As Date = CDate(....)

workRow("Date") = dateReceived

dv = New DataView(ReportTable)
dv.Sort = "Date Desc"

This sorts, but sorts by the string value of the date instead of the date.

How can I get it to sort by date value instead of the string value?

Thanks.
 
Hi Gerhard,

For the further question about the "Date" column, it is caused by the way
you create the "Date" column(as below):

ReportTable.Columns.Add("Date")

The above method will always create a new column in DataTable and set its
datatype to "String". That's why you found that the values in the "Date"
column are sorted as string values. To make them work as DateTime instance,
you need to specify the datatype(as DateTime) when creating the column. e.g.

===============
Dim ReportTable As New DataTable

'specify the type of the column as DateTime

ReportTable.Columns.Add("Date", GetType(DateTime))
===============

Hope this helps.


Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead


This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top