Sort Datagridview Column by date.
I have a column with dates on it and I'm trying to sort it according to that.
Code:
DataGridView2.Columns("0").DefaultCellStyle.Format = "dd/mm/yy"
DataGridView2.Sort(DataGridView2.Columns("0"), ListSortDirection.Descending)
I tried to use this but it only sorts by the first two digits, dd, and not with the full date.
I searched but couldn't find anything, any idea?
Thanks.
Re: Sort Datagridview Column by date.
is the datagridview is binded to a data source
Re: Sort Datagridview Column by date.
Quote:
Originally Posted by
make me rain
is the datagridview is binded to a data source
No, I'm reading a csv file using StreamReader.
Re: Sort Datagridview Column by date.
so, why cant you set the column -> defaultcellstyle -> datagridviewdefaultcellstyle
in design view
which is the easiest way out
Re: Sort Datagridview Column by date.
I'm adding the columns by code.
I tried that - I think It does the same as the code.
If I have three dates on that column, lets say:
29/11/2006
31/10/2009
29/12/2010
It sorts like this:
31/10/2009
29/12/2010
29/11/2006
Re: Sort Datagridview Column by date.
exactly i am unable to visualize your problem,but it should work PROVIDED if you set the datagridview cell format property well before filling the DGV.
any how try this
here i am adding one column & then i am seting the cell format of the column & then filling the dates
just check to sort by clicking on the column header and reply
vb Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
Dim StartDate As Date = System.DateTime.Now
Dim C As New DataGridViewTextBoxColumn()
C.Name = "Cx"
C.HeaderText = "dx"
With Me.DataGridView1
.Columns.Add(C)
.Columns(0).DefaultCellStyle.Format = "d"
For i = 0 To 10
.Rows.Add(1)
.Rows(i).Cells(0).Value = _
DateAdd("d", i, StartDate)
Next
End With
End Sub
Re: Sort Datagridview Column by date.
Re: Sort Datagridview Column by date.
you don't need to set the DefaultCellStyle.
your dgv will sort properly if you add the values as dates + not as strings