Sunday, April 12, 2009

Reading List items in datatable

Some time you want to read the items from the list and get it in a datatable for additional processing before binding it to any control.

SPListItemCollection exposes GetDataTable() method to make your life easier.


SPWeb web= SPContext.Current.Web;
SPList list = web.Lists["List_Name"];
SPListItemCollection collListItems = list.Items;
DataTable dt = collListItems.GetDataTable();

// To do ( You can do the processing here )

GridView1.DataSource = dt;
If you want to bind the table to SPGridView , make sure to add the columns first as SPGridView usually have AutoGenerateColumn property set to false.

You can use the same with SPQuery also as it returns SPListItemCollection only.

DataTable you will be getting is in dis-connected mode so good fit for display only information. This will not work in case you want to update list items.

There is always some catch :-)