Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a DataGridView column (tied to a BindingSource) by date?

I've got a DataGridView which, amongst others, has columns containing dates. Unfortunately, the dates are in the format DD.MM.YYYY and the whole value is in 1 column, which is the common date format here in Europe. The DGV is tied to a BindingSource which is capable of sorting and advanced sorting.

The problem is the following: If I just use the standard sorting of the DGV, the dates are viewed as strings (they're displayed in a DataGridViewTextBoxColumn) and thus sorted by day->month->year but of course I'd want exactly the opposite; I want them sorted chronologically.

So, is there a way to sort this columns the way I want them to?

  • By far the easiest way would be to be able to use the SortCompare event of the DGV but apparently that can't be done if the DGV is tied to a DataSoruce.
  • Of course I used Google and I always get the "use the Sort property for advanced sorting" solution. The BindingSource that's tied to the DGV indeed does support sorting and advanced sorting but as I understand it, this just gives me the possibility to e.g. sort by multiple columns and doesn't provide a way to make it sort the date column by year->month->day (or in more general terms allows me to implement a kind of compare function). Or am I missing something?

What options do I have to achiev what I want? When explaining, please keep in mind that I'm -althoug not new to programming- new to this Windows Forms stuff.

Thanks in advance!

like image 785
Yuk Avatar asked Nov 13 '22 09:11

Yuk


1 Answers

private void DataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    if (e.Column.Name == "YourColumnName") //<== this must be your date column name
    {
        DateTime dt1 = Convert.ToDateTime(e.CellValue1);
        DateTime dt2 = Convert.ToDateTime(e.CellValue2);
        e.SortResult = System.DateTime.Compare(dt1, dt2);
        e.Handled = true;
    }
}
like image 185
Tansel Korkmaz Avatar answered Nov 16 '22 02:11

Tansel Korkmaz