|
-
Jan 19th, 2012, 11:02 AM
#1
Thread Starter
Hyperactive Member
Datagrid Multiple Column Sort
Hello there,
I have a table with two columns, date and time. I am using the following code to sort in descending date order.
VB Code:
If historydataGrid.Rows.Count > 0 Then
'if there are rows, sort by date (most recent first)
historydataGrid.Sort(historydataGrid.Columns(0), System.ComponentModel.ListSortDirection.Descending)
End If
Where Columns(0) is the Date. However, how difficult is it for me to then sort secondarily by time. So that the grid will sort by most recent date and time.. Working down from the most recent time on the most recent date, and then moving backwards towards the oldest date with the oldest time.
Cheers!
-
Jan 19th, 2012, 05:20 PM
#2
Re: Datagrid Multiple Column Sort
you'd need to use an IComparer:
vb Code:
Public Class comparer
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim xRow As DataGridViewRow = DirectCast(x, DataGridViewRow)
Dim yRow As DataGridViewRow = DirectCast(y, DataGridViewRow)
If Date.ParseExact(yRow.Cells("dateField").Value.ToString, "dd/MM/yyyy", CultureInfo.CurrentCulture) > Date.ParseExact(xRow.Cells("dateField").Value.ToString, "dd/MM/yyyy", CultureInfo.CurrentCulture) Then
Return 1
ElseIf Date.ParseExact(yRow.Cells("dateField").Value.ToString, "dd/MM/yyyy", CultureInfo.CurrentCulture) < Date.ParseExact(xRow.Cells("dateField").Value.ToString, "dd/MM/yyyy", CultureInfo.CurrentCulture) Then
Return -1
Else
Return TimeSpan.Parse(yRow.Cells("timeField").Value.ToString).CompareTo(TimeSpan.Parse(xRow.Cells("timeField").Value.ToString))
End If
End Function
End Class
add the comparer to your project + use it like this:
vb Code:
DataGridView1.Sort(New comparer)
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Jan 20th, 2012, 07:42 AM
#3
Thread Starter
Hyperactive Member
Re: Datagrid Multiple Column Sort
Thanks Paul. I feared I would have to use this class. I really dislike it. Hey-ho. Thanks for the info. The forums won't let me give you any more rep at the moment. :/
-
Jan 20th, 2012, 08:21 AM
#4
Re: Datagrid Multiple Column Sort
Another idea is to sort on the data, assign your DataTable to a BindingSource which becomes the DataSource for the DataGridView. Set the sort property of the BindingSource to multiple columns i.e. BindingSource1.Sort = "Col1,Col2 desc"
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|