Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting dates in DataGridView

I'm pulling different info from a SQL table using sqlDataReader. One of the columns contains DateTime, and is pulled from the sql and displayed correctly, using:

var datestring = reader.GetDateTime(reader.GetOrdinal("deadline")).ToShortDateString();

It is shown in the DataGridView in the following format: dd.MM.yyyy

When I try to sort this, it sorts it after dd, no matter what the MM and yyyy info is.

The datestring is put in the datagridview with the following command:

dgv_tasks.Rows.Add(tid, taskname, sidvariable, datestring);

Anyone knows why it's not sorting this as dates at all, just the number in dd ?

(I've looked here for an answer, but none of the similar questions had a working answer).

like image 339
Skram Avatar asked Dec 06 '22 22:12

Skram


1 Answers

You want to leave it as a DateTime in the DataGridView, not convert it to a string. That's why it's sorting alphabetically, instead of by date.

Remove .ToShortDateString() and define your DataGridViewColumn as a DateTime type (assuming you're creating the columns manually).

After assigning the data to the DataGridView, just modify that column's DefaultCellStyle.Format value to display the date in whatever you manner you choose:

dgv_tasks.Columns["deadline"].DefaultCellStyle.Format = "dd.MM.yyyy";
like image 155
Grant Winney Avatar answered Dec 24 '22 15:12

Grant Winney