Monday, December 12, 2011

Binding an ASP.NET dropdown list to a SharePoint list

Quick code snippet to populate an ASP.NET dropdown list from a SharePoint list. Also note that there is no need to use a foreach loop to iterate through the items collection, adding the items to the list blablabla. I simply create an SPList instance, retrieve the data from the appropriate list and then tie those two bastards down. That's how I do stuff, yo.
using (SPWeb web = SPContext.Current.Site.OpenWeb())
                SPList list = web.Lists["TestConnectionList"];
                ddlConnections.DataSource = list.Items;
                ddlConnections.DataValueField = "Title";
                ddlConnections.DataTextField = "Title";
In this case, the name of the resource SharePoint list is called 'TestConnectionList' and the name of the dropdown list 'ddlConnections'. Make sure that you also specify the exact same column names in the list in the DataValueField and DataTextField or otherwise you'll get an exception thrown at you. As you can see, I am also using a scope so that the SPWeb object gets destroyed after usage. This is because I am explicitly calling the site.OpenWeb();

No comments:

Post a Comment