• How to Bind List string to Dropdownlist

    Posted on August 15, 2012 by in Dotnet Tips & Tricks, Tips & Tricks

    Create a simple ASP.NET page with  a drop down list as shown below:

    <html>
    <head runat="server">
        <title></title>    
    </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <asp:DropDownList ID="ddlProducts" runat="server"></asp:DropDownList>
        </div>
        </form>
    </body>
    </html>
    

    Solution 1:
    In the Page_Load event, create a sample product list. In order to bind it to a dropdown we need to convert this list into a dictionary object using LINQ. Later we could simply bind the dropdownlist to the dictionary object.

    protected void Page_Load(object sender, EventArgs e)
    {
        //populate a list object with sample data            
        List<string> products = new List<string>();            
        products.Add("Adjustable Race");
        products.Add("Bearing Ball");
        products.Add("BB Ball Bearing");
        products.Add("Headset Ball Bearings");
    
        Dictionary<string, string> productsHash = products.ToDictionary(product => product);
        
        //Sets the field of the data source that provides the text content
        //of the list items.
        ddlProducts.DataTextField = "Value";
    
        //Set the field of the data source that provides the value of each
        //list item.
        ddlProducts.DataValueField = "Key";
        
        //set the data source
        ddlProducts.DataSource = productsHash;            
        ddlProducts.DataBind();
    }
    

    Solution 2:

    In the Page_Load event, create a sample product list. You could directly bind the list to the dropdownlist as shown below:

    protected void Page_Load(object sender, EventArgs e)
    {
        //populate a list object with sample data            
        List<string> products = new List<string>();            
        products.Add("Adjustable Race");
        products.Add("Bearing Ball");
        products.Add("BB Ball Bearing");
        products.Add("Headset Ball Bearings");
            
        //set the data source
        ddlProducts.DataSource = products;            
        ddlProducts.DataBind();
    }
    

    Run the page and you would notice that the drop down list is populated with the products list.
    Bind List string to Dropdownlist 1

    Be Sociable, Share!
      Post Tagged with , , ,

    Written by

    View all articles by

    Email : [email protected]

    Leave a Reply