Sunday, November 16, 2008

Programatically Reading a list and binding to SPGridView (Code)

This post would depict the simple usage of SPGridView and reading from a list and binding it to the SPGridView programatically.


SPGridView oSPGridView = new SPGridView();
string sTaskListName = "News"; // News List in this example

SPWeb site = SPControl.GetContextWeb(Context);
SPList spList = site.Lists[sTaskListName];

SPDataSource mySPDS = new SPDataSource();
mySPDS.List = spList;

oSPGridView.DataSource = mySPDS;
oSPGridView.DataBind();

2 comments:

Sandeep K Nahta said...

I think you need to set the correct mode for SPDataSource. DataSourceMode = List ; first to use it ..check once

Srini Sistla said...

I will admit, it is definetly good practise to use SPDataSourceMode.

However the above code works good and setting up this property is not mandate. Although the valid modes are List, Listitem, listoflists, webs and crosslist as that are mentioned in books... its works very well with datatable or a dataview too. Reason?

As a matter of fact, any data source control (that implements IDataSource interface) can directly connect to this data-bound control (SPGridView) with out setting the mode property. The reason is, it internally implements other interfaces (one of them is IListSource) that take care of binding.