I am retrieving some dates from a list column in my SharePoint

 SPList taskList = site.Lists["mylist"];
 SPListItemCollection taskListItems = taskList.Items;

foreach (SPListItem item in taskListItems)
           DateTime birthday = Convert.ToDateTime(item["Birthday"]);

Now I want items to be sorted in Ascending, How can I do that?


  • do you want to bind sorted items to somewhere? if yes, is it custom control like gridview or repeater? – love thakker Sep 22 '16 at 7:45
  • yes I am binding them in gridview @lovethakker – Iamnderon Sep 22 '16 at 7:50

Besid the CAML query solution , You can do this without code by edit your custom view and perform Sort to your column .

enter image description here

Then in your code you can GetItems by your custom view.

SPView yourView = CurrentList.Views[your custom view name];
SPListItemCollection taskListItems = taskList.GetItems(yourView);
Gridview.DataSource = taskListItems.GetDataTable();

Also, when you retrive taskListItems at SPListItemCollection to datatable and write this code

SPListItemCollection taskListItems = taskList.Items;
DataTable dt = taskListItems.GetDataTable(); 
// Create dataview    
DataView dv = dt.DefaultView;
dv.Sort = "the column name ASC"; // DESC for desinding order

Then bind dv dataview to your Gridview datsource (as you mentioned at your question comments you are using Gridview)

Gridview.DataSource= dv;

You can directly fetch items in ascending order in CAML query. Please try to add following in your CAML query->

   <FieldRef Name='Birthday' Ascending='True'/>

Here "Birthday" will be your DateTime column on which sorted data will be retrieved.

  • yes but how can I sort only month and day because if I want at top of grid view to be shown those who have birthday recently – Iamnderon Sep 22 '16 at 8:15

One of solution is that you add this things in data table and using data view you can sort them. Then you can bind the view to grid view.

Second option is you use CAML query to get SPLIstItemCollection. In CAML you can fetch data in ascending order automatically.

  • I have to use the first solution, can you show me how to implement it please? – Iamnderon Sep 22 '16 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.