In this post, we’ll show How to programmatically populate dropdown from SharePoint List using C#?
You might also like to read Show / Hide fields based on choice field selection using JQuery in SharePoint 2016.
Consider, you have a city list in SharePoint, you need to retrieve a specific field value to a Dropdown list in Visual Web Part in C#.
Let’s define the dropdown list in front code as the following:
<asp:DropDownList ID="dlCountry" runat="server" AutoPostBack="true">
</asp:DropDownList>
Now, we are gonna create a function to bind a specific field to a dropdown list as shown below
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();
}
}
}
Get a specific field into a dropdown list based on CAML Query in C#
In case, you are using CAML query to retrieve your list item collection, you can use the below code:
public void BindCountry() {
using(SPSite site = new SPSite(SPContext.Current.Site.Url)) {
using(SPWeb web = site.OpenWeb()) {
SPList list = web.Lists["Country"];
SPQuery query = new SPQuery();
query.Query = "<View><ViewFields><FieldRef Name='Title'/></ViewFields></View>";
SPListItemCollection Items = list.GetItems(query);
foreach (SPListItem Item in Items)
{
dlCountry.Items.Add(new ListItem(Item.Title));
}
}
}
}
The above code is working for CheckBox List as well, you just need to set the control name at “dlCountry.Items.Add”
Finally, call the “BIND()” function In Page_Load as shown below
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
BindCountry();
}
You might also like to read Work with SharePoint Lookup Field Programmatically
Conclusion
In conclusion, we have learned how to Populate dropdown from SharePoint List using C# as well as how to Get a specific SharePoint field into a dropdown list based on CAML Query in C#.
Applies To
- SharePoint 2016.
- SharePoint 2013.
- SharePoint 2010.
- C# SSOM.
You may also like to read
- Get and Set a SharePoint URL Field Value Using Server Object Model C#.
- Get and Set a SharePoint Multiple Choice Field Value Using Server Object Model C#.
- Get and Set a SharePoint Multiple Lookup Field Value Using Server Object Model C#.
Have a Question?
If you have any related questions, please don’t hesitate to ask it at deBUG.to Community.
Pingback: Get SharePoint Choice Field Value In C# | SPGeeks