Question

I am trying to write a visual part in visual studio 2015 to create a form. There is a drop down list of countries. How can I create this drop down using C#?

Was it helpful?

Solution

First create a SharePoint custom list named Country. Then add all the country names into that list.

Now you can read data from that list and populate the dropdown

  1. Get list object using

    using(SPSite site = new SPSite(SPContext.Current.Site.Url) {
       using(SPWeb web = site.OpenWeb() {
             SPList list = web.Lists.TryGetList("Country");
    
  2. Now you can use Items property to get all items and populate the drop down using

    foreach(SPListItem item in list.Items) {
         ddlCountry.Items.Add(item["Title"].ToString());
    }
    

OTHER TIPS

  • Open Visual Studio
  • Create empty SharePoint project
  • Add Visual WebPart to it.
  • Rename and provide group name.
  • Go to your visual webpart (.ascx) file
  • In the bottom of page. Add your HTML code (including dropdown)
  • If you want you can add the country values directly in html block for ex.

      <asp:DropDownList ID="ddlCountry" runat="server" Width="200px">
       <asp:ListItem >India</asp:ListItem>
       <asp:ListItem >US</asp:ListItem>
       <asp:ListItem >UK</asp:ListItem>
     </asp:DropDownList>
    

Or

      <asp:DropDownList ID="ddlCountry" runat="server" Width="200px"/>

Do not assign values if you want them to bind from some source. like list.
- Go to code behind (.ascx.cs)
- In Page Load method fetch the data from list and assign it to dropdown.

There you go.

Below is he link which creates three DropDownList to display countries, states and cities. When you select a country then its automatically shows the states name of that country in next DropDownList. Then when you select a state, the cities DropDownList will fetch the related cities for that state.

DropDownList with country, state and city in ASP. NET

You will also get the idea from above article that how you can create a dropdown list in C#

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top