3

I have a gridview with some columns and I need to sort the gridview by a date-column. But I fail in sorting it correctly. This is the code that I use:

dt.DefaultView.Sort = "Meldingsdatum asc";
gvOutlookMeldingen.DataSource = dt;
gvOutlookMeldingen.DataBind();

Can someone help me, please.

Tassisto
  • 9,877
  • 28
  • 100
  • 157

4 Answers4

3

http://forums.asp.net/p/1267353/2393006.aspx

sajoshi
  • 2,733
  • 1
  • 18
  • 22
  • 1
    not really an answer but a link to it. post an answer so I can accept it – Tassisto Mar 21 '11 at 08:48
  • The answer there, as openshac has suggested as well, is: "Check the DataType property of the DataColumn and make sure it's set to DateTime." – DOK May 23 '13 at 14:32
2

DataView stores date or anything as string type. Thus when you sort it sort by string. To sort it as DateTime , you need to convert it to DateTime before adding any data as follows,

dt.Columns["Date"].DataType = Type.GetType("System.DateTime");

2

My code snippet hopefully shows the need to set the column as typeof(DateTime) before you can sort it properly

        EntityCollection result = serviceProxy.RetrieveMultiple(querybyattribute);

        DataTable dt = new DataTable();
        dt.Columns.Add("Title");
        dt.Columns.Add("Created On", typeof(DateTime));

        foreach (Entity entity in result.Entities)
        {
            DataRow dr = dt.NewRow();

            dr["Title"] = entity.Attributes["title"].ToString();
            dr["Created On"] = entity.Attributes["createdon"];

            dt.Rows.Add(dr);
        }

        DataView dv = dt.DefaultView;
        dv.Sort = "Created On desc";
        DataTable sortedDT = dv.ToTable();

        dataGridView1.DataSource = sortedDT;
Dennis
  • 43
  • 7
1

Is you column of type DateTime, if not then it probably needs to be. Do this right at the start before you populate the table. Alternatively you could create a second column of type DateTime and use that but it's a little messy :-)

openshac
  • 4,966
  • 5
  • 46
  • 77