Several Ways to populate DropDownList Controls

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 137655 red flag
Rating: 4.6 out of 5  
 5 vote(s)

There are several ways to populate DropDownList control. In this article I have tried to cover some of them including populating DropDownList manually, programmatically, through xml, database, arraylist, hashtable. I have also covered how to specify different background color of every items of the DropDownList and how to generate DropDownList on the fly. At last I have covered how to get its index, text and value properties.


 Download source code for Several Ways to populate DropDownList Controls

Here one thing is worth mentioning that DropDownList is rendered as the Select HTML tag in your page. Let’s start with different ways of populating DropDownList server controls first.





Populating DropDownList control manually


<asp:DropDownList ID="dropManually" runat="Server">
<asp:ListItem Text="Option 1" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Option 3" Value="3"></asp:ListItem>
<asp:ListItem Text="Option 4" Value="4"></asp:ListItem>
</asp:DropDownList>

Here you need to write the asp:ListItem tag for every item you want to appear in the DropDownList.

Populating DropDownList control through server side code



dropServerSide.Items.Add(new ListItem("Option 1", "1"));
dropServerSide.Items.Add(new ListItem("Option 2", "2"));
dropServerSide.Items.Add(new ListItem("Option 3", "3"));
dropServerSide.Items.Add(new ListItem("Option 4", "4"));



Here you need to call DropDownList.Items.Add method and pass ListItem as the parameter.

Populating DropDownList control through database/xml file



DataSet dSet = new DataSet();
string strDataFileName = Server.MapPath("GridData.xml");
try
{
dSet.ReadXml(strDataFileName);
dropList.DataSource = dSet.Tables[0].DefaultView;
dropList.DataBind();
}
catch (Exception ee)
{
lblError.Text = ee.ToString();
}
finally
{
dSet.Dispose();
}

In the above code, I am getting the xml data into the DataSet and retrieving the table from it and setting DataSource property of DropDownList and then calling DataBind() of DropDownList control. Here note that unless you call DataBind() method you will not see any items in the DropDownList even if you have specified the DataSource property. In the same way you can get the records from database into DataSet and populate the DropDownList.

Before you specify DataSource property, you should specify the DataTextField property and DataValueField of the DropDownList so that while binding the data the ListItem text will be written as DataTextField value and ListItem value will be written as DataValueField value.


Adding another item to the existing DropDownList


// Now lets add another item to the DropDownList
string listItemText = "New Item";
string listItemValue = "New Value";

dropList.Items.Add(new ListItem(listItemText, listItemValue));

// Now lets select it by finding the item by its value
dropList.Items.FindByValue(listItemValue).Selected = true;


Here, first I am declaring two variables for list item text and list item value and then calling Add method of the DropDownList Items and passing ListItem as the parameter with text and value inside it. To select the added item, I am using FindByValue method of the DropDowList Items and making its Selected property as true. In the same way you can use FindByText property of the DropDownList Items if you want to find the items by its text.


Selecting a particular item while binding the DropDownList


<asp:DropDownList ID="dropDataBaseSelectWhileBinding" runat="Server" DataTextField="FirstName" DataValueField="LastName" SelectedValue='<%# strSelectedValue %>' />


Here, I am specifying SelectedValue property of the DropDownList to a value that should be one of the items values of the DropDownList. In my code, I have specified one of the values of the DropDownList into strSelectedValue variable. In real scenario, you may specify your DataValueField as SelectedValue = ‘<%# Eval(“LastName”) %>’.


Specifying different background color for every items of the DropDownList


// First populate the DropDownList
PopulateDropDownListThroughDatabase(dropList);
// Now add style attributes with different background color
dropList.Items[0].Attributes.Add("style", "background-color:#dfjlef;");
dropList.Items[1].Attributes.Add("style", "background-color:yellow;");
dropList.Items[2].Attributes.Add("style", "background-color:#77ee33;");
dropList.Items[3].Attributes.Add("style", "background-color:red;");


First you should populate the DropDownList then add each items style attributes to different color. When this will render it will add Style attributes of that item as follow

<option value="Narayan" style="background-color:#dfjlef;" >Sheo</option>)

Populating DropDownList using ArrayList


ArrayList aList = new ArrayList();
aList.Add("ArrayList Item 1");
aList.Add("ArrayList Item 2");
aList.Add("ArrayList Item 3");
aList.Add("ArrayList Item 4");

dropArrayList.DataSource = aList;
dropArrayList.DataBind();



Here, I have declared an ArrayList first and added 4 items (ArrayList add items as an object) into it then I specified the DataSource property of the DropDownList and called DataBind() method. This will bind the DropDownList with the items of the ArrayList. In this case the text and value property of the ListItem will be same (ie. For 1st item the text and value property of the item will be “ArrayList Item 1”)

Populating DropDownList using HashTable



Hashtable hTable = new Hashtable();
hTable.Add("1", "Hashtable Item 1");
hTable.Add("2", "Hashtable Item 2");
hTable.Add("3", "Hashtable Item 3");
hTable.Add("4", "Hashtable Item 4");

dropHashtable.DataSource = hTable;
dropHashtable.DataBind();


Here, I have declared a Hashtable and added 4 elements into it (Hashtable stores data into key and value pairs) and then specified DataSource property of the DropDownList to it. After that as usual we need to call DataBind() method of the DropDownList. Please note that in this case you should specify DataTextField and DataValueField property of the DropDownList otherwise you will only see System.Collections.DictionaryEntry as the text and value of the DropDownList item. Here I have specified key as the DataValueField and value as the DataTextField property.

Creating DropDownList on the fly


DropDownList dropList = new DropDownList();
dropList.ID = "dropOnTheFly";
// Manually populate the value
dropList.Items.Add(new ListItem("On the fly item 1", "1"));
dropList.Items.Add(new ListItem("On the fly item 2", "2"));
dropList.Items.Add(new ListItem("On the fly item 3", "3"));

placeHolder1.Controls.Add(dropList);

Here, I have declared a DropDownList variable and specified its ID property. This ID property should be unique in your page. Then I have added items to this DropDownList. Instead of manually adding Items you could have specified the DataSource property too. Once I have items into it, I have added this control to the PlaceHolder control on my page.

Getting Selected Text, Value and Index of the DropDownList


labSelectedValue.Text = dropDatabaseAddAndSelect.SelectedValue;
labSelectedText.Text = dropDatabaseAddAndSelect.SelectedItem.Text;
labSelectedIndex.Text = dropDatabaseAddAndSelect.SelectedIndex.ToString();

To get the Selected value I have called SelectedValue property of the DropDownList. To get the selected items text I have called the text property of the SelectedItem of the DropDownList. To get the selected Index I called SelectedIndex property of the DropDownList.


Hope this example helps some of you. You may want to download the source code of this example from the top-right download link. If you have any question or suggestions, please let me know.

Thanks and Happy Coding !!!
Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)