asp.net dropdownlist add item after databind
The following asp.net c# example code demonstrate us how can we add an item to DropDownList server
control after data bind. We can populate a DropDownList programmatically at run time by data binding with
various data sources such as Array, SqlDataSource, ObjectDataSource etc. We only need to specify the DropDownList
DataSource and after that call the DataBind() method.
After data binding a DropDownList control we can add or insert an item to its items collection. In this example code we uses items collection Insert() method to add an item to DropDownList. Insert() method allow us to insert an item to DropDownList at any index position because it has a required parameter to pass index value.
After data binding a DropDownList control we can add or insert an item to its items collection. In this example code we uses items collection Insert() method to add an item to DropDownList. Insert() method allow us to insert an item to DropDownList at any index position because it has a required parameter to pass index value.
dropdownlist-add-item-after-databind.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] birds = { "King Penguin", "Gentoo Penguin", "Adelie Penguin", "Fairy Penguin" };
DropDownList1.DataSource = birds;
DropDownList1.DataBind();
ListItem li = new ListItem();
li.Text = "Wandering Albatross";
li.Value = "6";
//this line add list item at list top after data bind.
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 after databind</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net example - dropdownlist add item after databind
</h2>
<hr width="550" align="left" color="Gainsboro" />
<br /><br />
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
>
</asp:DropDownList>
</div>
</form>
</body>
</html>
- How to add a blank item at the top of DropDownList
- How to reset DropDownList on postback
- How to get DropDownList selected item without postback
- How to change DropDownList alternate item color
- How to change DropDownList selected item color
- How to change DropDownList item background color
- How to highlight an item in a DropDownList
- How to change DropDownList selected item text and background color
- How to remove arraow from DropDownList
- How to change DropDownList arrow image