Bind a dropdown from SharePoint List via c#

In this hint,  I’ll show How to bind a dropdown from SharePoint List via c#.

I have a country list in SharePoint, I need to retrieve all SharePoint list items to a Dropdown list in Visual Web Part.

Code:

Front Code:

<asp:DropDownList ID="dlCountry" runat="server" AutoPostBack="true">
</asp:DropDownList>

Code Behind:

public void BindCountry()
{
   using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists["Country"];
            DataTable dt = list.Items.GetDataTable();
            dlCountry.DataSource = dt;
            dlCountry.DataTextField = "Title";
            dlCountry.DataValueField = "ID";
            dlCountry.DataBind();
        }
    }
}

In page Load event, call your function.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    BindCountry();
}

Enjoy 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s