asp.net dropdownlist add item at index 0
DropDownList is an asp.net web server control. we can add an item to dropdownlist but it will displayed it at
the bottom of dropdownlist control. so we need to apply few
techniques to add a new item at the top of dropdownlist.
dropdownlist items collection Insert() method allow us to insert new item at specified index position of dropdownlist items collection. if we insert the new item to dropdownlist items collection at index 0 then it will display the newly added item in dropdownlist top position.
the following asp.net c# example code demonstrate us how can we add an item to dropdownlist at index position 0 (zero) in an asp.net application.
dropdownlist items collection Insert() method allow us to insert new item at specified index position of dropdownlist items collection. if we insert the new item to dropdownlist items collection at index 0 then it will display the newly added item in dropdownlist top position.
the following asp.net c# example code demonstrate us how can we add an item to dropdownlist at index position 0 (zero) in an asp.net application.
dropdownlist-add-item-at-index-0.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ListItem li = new ListItem();
li.Text = "Emperor Penguin";
li.Value = "6";
//this line add list item at list top (index 0) position
DropDownList1.Items.Insert(0, li);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net dropdownlist add item at index 0</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net example - dropdownlist add item at index 0
</h2>
<hr width="550" align="left" color="Gainsboro" />
<br /><br />
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
>
<asp:ListItem Text="Smew" Value="1"></asp:ListItem>
<asp:ListItem Text="Common Merganser" Value="2"></asp:ListItem>
<asp:ListItem Text="Emperor Penguin" Value="3"></asp:ListItem>
<asp:ListItem Text="Ruddy Duck" Value="4"></asp:ListItem>
<asp:ListItem Text="Musk Duck" Value="5"></asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>

- How to get DropDownList selected value by selectedindexchanged event
- How to set a default value for DropDownList
- How to add an item at the top of DropDownList
- How to sort DropDownList items alphabetically
- How to sort DropDownList items by text
- How to sort DropDownList items by value
- How to sort DropDownList items in descending order
- How to select DropDownList item by value
- How to select DropDownList item by item text
- How to create a DropDownList displaying years