Sunday, April 12, 2009

Reading List items in datatable

Scenario:
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.

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

Code:

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;
GridView1.DataBind();
Note:
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 :-)

0 comments: