03 June 2010

Retrieve SharePoint List Data and Bind to a DropDownList in ASP.NET

If you have a SharePoint List within a Site, and want to bind the first column of that list to a DropDownList using ASP.NET, then the following steps are what you need to do:

For this example, we are assuming your SharePoint Site URL is: http://mysharepointsite
The name of the SharePoint List (which must reside within the above site!) is called ExampleList.
You need to place the following code within the Page_Load event:

if (!Page.IsPostBack)
     {
        using (SPSite site = new SPSite("http://mysharepointsite"))      
       {
          using (SPWeb web = site.OpenWeb())
           {
             SPList list = web.Lists["ExampleList"];
             dropSite.DataSource = list.Items;
             dropSite.DataValueField = "Title"; //Value Property- first column is called Title
             dropSite.DataTextField = "Title"; //Text property that is displayed on page 
             dropSite.DataBind();
           }
        }
     }
Hope that helps!
Regards, Ash

No comments:

Post a Comment