[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Datagridview sorting by date

Posted on 2010-01-06
15
Medium Priority
?
2,638 Views
Last Modified: 2012-05-08
Currently I have a datagridview that I created the columns at run time and added data to it row by row. (No databinding) How do I make a column that has dates (01/01/2009) sortable by the date? It appears to interpret it as a string is there a way to say this is a date column treat it like a date not a string. I tried creating a cell template but it doesn't work. Do I have to make the data into YYYY-MM-DD format somehow when the user clicks the header and then switch it back?

Dim txtCelldate As DataGridViewCell = New DataGridViewTextBoxCell
        With txtCelldate
            'Put specifics about the cell here, such as backcolor, etc.
            .Style.Format = "DD/MM/YYYY"
        End With
0
Comment
Question by:cobolinx1
  • 5
  • 5
  • 3
  • +1
15 Comments
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26190582
u need to set the ValueType property of the column to DateTime, check this code snippet:
dataGridView1.ColumnCount = 3
dataGridView1.Columns(0).Name = "ID"
dataGridView1.Columns(0).ValueType = GetType(Integer)

dataGridView1.Columns(1).Name = "Name"
dataGridView1.Columns(1).ValueType = GetType(String)

dataGridView1.Columns(2).Name = "Date"
dataGridView1.Columns(2).ValueType = GetType(DateTime)

Open in new window

0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26190586
the 3rd column is type of DateTime and it expects DateTime objects...
0
 
LVL 27

Expert Comment

by:VBRocks
ID: 26190705
The other alternative is to use something like a DataTable, and set it as the DataSource of the DataGridView.  But either way, the column that has the Date in it needs to be of a Date data type, like sedqwick explained.  

The benefit of using a DataTable is that it is very easy to work with, is sortable, and can be filtered very easy, which you won't be able to do just using the DataGridView.

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:cobolinx1
ID: 26190777
I still treats the dates as strings when I sort them.
0
 

Author Comment

by:cobolinx1
ID: 26190864
The problem with setting the datasource is that I have data that I need to convert before displaying it and there are some combobox fields that I have a datasource already associated with it so If the user clicks on the field there are values that may not be in the dataset that I would bind everything to.
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26191070
from msdn:
The default sort mode of a DataGridViewTextBoxColumn is Automatic.
The default sort mode for other column types is NotSortable.

u can set SortMode property of the column to DataGridViewColumnSortMode.Automatic,
so if the ValueType is DateTime it will sort the column accordingly.
0
 
LVL 27

Expert Comment

by:VBRocks
ID: 26191138
cobolinx,

Can you show me how you are populating the DataGridView?

0
 

Author Comment

by:cobolinx1
ID: 26191370
I have it set to automatic.

  If dssubmissions.Tables(0).Rows.Count > 0 Then
            Dim i As Integer = 0
            While i < dssubmissions.Tables(0).Rows.Count
                dgvsubmissions.Rows.Add(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
                dgvsubmissions.Rows(i).Cells("Sub ID").Value = dssubmissions.Tables(0).Rows(i).Item("Submission ID").ToString
                dgvsubmissions.Rows(i).Cells("PRO_ID").Value = dssubmissions.Tables(0).Rows(i).Item("PRO_ID").ToString
                dgvsubmissions.Rows(i).Cells("PrO_NAME").Value = dssubmissions.Tables(0).Rows(i).Item("PRONAME").ToString
             

                Try
                    dgvsubmissions.Rows(i).Cells("Type of Submission").Value = dssubmissions.Tables(0).Rows(i).Item("Type of Submission").ToString()

                Catch ex As Exception
                    Console.Write(ex.Message)
                End Try


                If dssubmissions.Tables(0).Rows(i).Item("Received Date").ToString().Trim <> "" Then
                    dgvsubmissions.Rows(i).Cells("Received Date").Value = CDate(dssubmissions.Tables(0).Rows(i).Item("Received Date")).ToShortDateString
                End If

                If dssubmissions.Tables(0).Rows(i).Item("Termination Date").ToString().Trim <> "" Then
                    dgvsubmissions.Rows(i).Cells("Termination Date").Value = CDate(dssubmissions.Tables(0).Rows(i).Item("Termination Date")).ToShortDateString
                End If

                dgvsubmissions.Rows(i).ReadOnly = True
                i +=  1
            End While
        End If
0
 
LVL 42

Accepted Solution

by:
Meir Rivkin earned 1000 total points
ID: 26191582
why ru calling ToShortDateString id u wish to have the values as DateTime?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 26191646
You can define a custom sort compare with the DataGridView.Sort method:

        dgvsubmissions.Sort(New DateTimeComparer())


Private Class DateTimeComparer
        Implements IComparer(Of DateTime)

        Public Function Compare(ByVal x As Date, ByVal y As Date) As Integer Implements System.Collections.Generic.IComparer(Of Date).Compare
            Return Date.Compare(x, y)
        End Function
    End Class

Open in new window

0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26191741
@TheLearnedOne

do i have 2 use custom sort comparer if the column type is datetime and sortmode is auto?
0
 

Author Comment

by:cobolinx1
ID: 26192278
I get an unable to cast object of type datetimecompairer to type system.collections.icompairer
0
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 1000 total points
ID: 26192451
Is the data that you are storing in the cells string or date/time?  

"I get an unable to cast object of type datetimecompairer to type system.collections.icompairer"
Is that a run-time error or a design-time error?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 26192511
That was a run-time error.

Here is a better example:


Private Class DescendingDateTimeComparer
        Implements IComparer

        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            Dim rowX As DataGridViewRow = CType(x, DataGridViewRow)
            Dim rowY As DataGridViewRow = CType(y, DataGridViewRow)
            Dim dateX As Date = rowX.Cells("DateColumn").Value
            Dim dateY As Date = rowY.Cells("DateColumn").Value
            Return Date.Compare(dateY, dateX)
        End Function
    End Class

Open in new window

0
 

Author Closing Comment

by:cobolinx1
ID: 31673462
You and sedgwik just made me realize something If I take the ToShortDateString off then it sorts fine.
0

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Loops Section Overview
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question