DopDownList
Dropdown List is one of the standard controls which we are using in a wide range.
This control restricts the user to select only one item.
Sample Code to do Operations with DopDownList
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
Code to Bind the Draopdown List with Data Source
DataSet ds = new DataSet();
ds = GetData();
//For binding data in Draopdown you need to specify which column is
//to displayed Draopdown and which column is the value filed.
//Otherwise Draopdown doesn't is in ambigious to show which column
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "ItemName";
DropDownList1.DataValueField = "ItemID";
DropDownList1.DataBind();
//Code to Add Items into Draopdown List
//By default it adds all list iltems from bottom level
string[] Weeks = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
for (int i = 0; i < Weeks.Length; i++)
{
ListItem li = new ListItem(Weeks[i], (i + 1).ToString());
DropDownList1.Items.Add(li);
}
//Code to Insert Items into Draopdown List
//if you want to insert a list item into Draopdown
//you need specify the location
DropDownList1.Items.Insert(0,
new ListItem("--Select One--", "-1"));
//Code to access the Draopdown list values
foreach (ListItem li in DropDownList1.Items)
{
if (Convert.ToInt32(li.Value) > 10)
{
Label1.Text += li.Text + "<br/>";
}
}
//Code to clear the selection
DropDownList1.ClearSelection();
//Code to remove all items from DropDownList
DropDownList1.Items.Clear();
//Code to make selected perticular item
//DropDownList deosn't supports muliple selection at a time,
//so for better coding Clear the Selection of items.
//Before goint to make seletion an item check weather
//that item is exist ot not.
if (DropDownList1.Items.Contains(DropDownList1.Items.FindByValue("11")))
{
DropDownList1.ClearSelection();
DropDownList1.Items.FindByValue("11").Selected = true;
}