Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

In this example I’m going to show the basic way on how to bind a different collections to a DropDownList control.

 

Note that you can also apply the code mentioned in this example to a ListBox, RadioButtonList and CheckBoxList. I just used DropDownList for this demo because I think it is the most commonly used in the page.

 

To get started, let’s go ahead and grab a DropDownList control from the Visual Studio toolbox and place it in the WebForm. The ASPX mark up should look something like below:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Bind Collections Demo</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:DropDownList ID="DropDownList1" runat="server">

        </asp:DropDownList>

    </div>

    </form>

</body>

</html>

 

Now let’s switch to Code-Behind part of the page. The first step to do is add the following namespaces below so that we can use the Collections object provided by .NET:

 

using System.Collections.Generic;

using System.Collections.Specialized;

 

After that, we can start creating a simple method that returns a data from a collection and bind it to the DropDownList control. Here are the code blocks below:

 

* Using a List

 

    private List<ListItem> GetDataFromList()

    {

        List<ListItem> myList = new List<ListItem>();

        myList.Add(new ListItem("Item 1", "Item 1 Value"));

        myList.Add(new ListItem("Item 2", "Item 2 Value"));

        myList.Add(new ListItem("Item 3", "Item 3 Value"));

 

        return myList;

    }

 

Binding the DropDownList with data from the List object.

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        //Manually adding the items to the DDL

        if (!Page.IsPostBack)

        {

            foreach (ListItem item in GetDataFromList())

            {

                DropDownList1.Items.Add(item);

            }

        }

      }

 

 

* Using a Dictionary

 

    private Dictionary<string,string> GetDataFromDictionary()

    {

        Dictionary<string, string> myDictionary = new Dictionary<string, string>();

        myDictionary.Add("Item 1 Value", "Item 1");

        myDictionary.Add("Item 2 Value", "Item 2");

        myDictionary.Add("Item 3 Value", "Item 3");

 

        return myDictionary;

    }

 

 

You can populate the DropDownList with the data from the Dictionary by (a) manually adding the items to it or (b) using the Dictionary directly as the DataSource and set the DataTextField and DataValueField to it. Check the following code blocks below:

 

(a)

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        // Manually adding the items to the DDL

        if (!Page.IsPostBack)

        {

            foreach (KeyValuePair<string, string> kValuePair in GetDataFromDictionary())

            {

                ListItem item = new ListItem(kValuePair.Value, kValuePair.Key);

                DropDownList1.Items.Add(item);

            }

        }

     }

 

(b)

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        //Using Dictionary as the DataSource of the DDL

        if (!Page.IsPostBack)

        {

            DropDownList1.DataSource = GetDataFromDictionary();

            DropDownList1.DataTextField = "Value";

            DropDownList1.DataValueField = "Key";

            DropDownList1.DataBind();

        }

    }

 

* Using a HashTable

 

    private Hashtable GetDataFromHash()

    {

        Hashtable myHash = new Hashtable();

        myHash.Add("Item 1 Value", "Item 1");

        myHash.Add("Item 2 Value", "Item 2");

        myHash.Add("Item 3 Value", "Item 3");

 

        return myHash;

    }

 

You can also populate the DropDownList in two ways just like what we did above using the Dictionary. Here are the code blocks below:

 

(a)

 

    protected void Page_Load(object sender, EventArgs e)

    {      

        // Manually adding the items to the DDL 

        if (!Page.IsPostBack)

        {

            foreach (DictionaryEntry entry in GetDataFromHash())

            {

                ListItem item = new ListItem(entry.Value.ToString(), entry.Key.ToString());

                DropDownList1.Items.Add(item);

            }

        }

    }

 

(b)

 

    protected void Page_Load(object sender, EventArgs e)

    {      

        //Using the HashTable as the DataSource of the DDL

        if (!Page.IsPostBack)

        {

            DropDownList1.DataSource = GetDataFromHash();

            DropDownList1.DataTextField = "Value";

            DropDownList1.DataValueField = "Key";

            DropDownList1.DataBind();

        }   

    }

 

* Using a SortedList

 

    private SortedList GetDataFromSortedList()

    {

        SortedList mySortedList = new SortedList();

        mySortedList.Add("Item 1 Value", "Item 1");

        mySortedList.Add("Item 2 Value", "Item 2");

        mySortedList.Add("Item 3 Value", "Item 3");

 

        return mySortedList;

    }

You can also populate the DropDownList in two ways just like what we did above. Here are the code blocks below:

 

(a)

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        if (!Page.IsPostBack)

        {

            foreach (DictionaryEntry entry in GetDataFromSortedList())

            {

                ListItem item = new ListItem(entry.Value.ToString(), entry.Key.ToString());

                DropDownList1.Items.Add(item);

            }

        }

    }

 

(b)

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        if (!Page.IsPostBack)

        {

            DropDownList1.DataSource = GetDataFromSortedList();

            DropDownList1.DataTextField = "Value";

            DropDownList1.DataValueField = "Key";

            DropDownList1.DataBind();

        }

    }

 

* Using an ArrayList

 

 

    private ArrayList GetDataFromArrayList()

    {

        ArrayList myArray = new ArrayList();

        myArray.Add(new ListItem("Item 1", "Item 1 Value"));

        myArray.Add(new ListItem("Item 2", "Item 2 Value"));

        myArray.Add(new ListItem("Item 3", "Item 3 Value"));

 

        return myArray;

    }

 

And here’s the code block for populating the DropDownList with data from ArrayList.

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        if (!Page.IsPostBack)

        {

            foreach (ListItem item in GetDataFromArrayList())

            {

                DropDownList1.Items.Add(item);

            }

        }   

    }

 

* Using a StringCollection

 

    private StringCollection GetDataFromStrCollection()

    {

        StringCollection myStrCol = new StringCollection();

        myStrCol.Add("Item1,Item 1 Value");

        myStrCol.Add("Item2,Item 2 Value");

        myStrCol.Add("Item3,Item 3 Value");

 

        return myStrCol;

    }

 

And here’s the code block for populating the DropDownList with data from StringCollection.

 

    protected void Page_Load(object sender, EventArgs e)

    {        

        if (!Page.IsPostBack)

        {

            string[] splitItem = null;

            foreach (String item in GetDataFromStrCollection())

            {

                if (item.Contains(","))

                {

                    splitItem = item.Split(",".ToCharArray());

                    ListItem newItem = new ListItem(splitItem[0].ToString(), splitItem[1].ToString());

                    DropDownList1.Items.Add(newItem);

                }

            }

        }   

    }

 

Running the code above will give this page output below:

 

 

That’s it! Hope you will find this example useful!

 

Technorati Tags: ,
Posted on Wednesday, July 8, 2009 6:47 PM ASP.NET , C# | Back to top


Comments on this post: How To: Bind Collections to a DropDownList Control

# re: How To: Bind Collections to a DropDownList Control
Requesting Gravatar...
nice info friend :)
well explaining
Left by Muthu Vijayan on Jan 13, 2010 12:34 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net