posted 10/27/2009 by Raghav Khunger
In this blog I will explain how to add item to dropdownlist after databind. I am talking about the scenario where we have bind the dropdownlist with some datasource and after binding the data we want to insert an item to dropdownlist in most cases at first option.
Below is the code:The heart of the code is at:
myDropdownList.Items.Insert(0,new ListItem("-- Please Select --","0"));
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList runat="server" ID="myDropdownList"> </asp:DropDownList> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Web.UI.WebControls; namespace TestProject { public partial class _Default : System.Web.UI.Page { /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { myDropdownList.DataSource = GetData(); myDropdownList.DataValueField = "ID"; myDropdownList.DataTextField = "Name"; myDropdownList.DataBind(); myDropdownList.Items.Insert(0,new ListItem("-- Please Select --","0")); } /// <summary> /// Gets the data. /// </summary> /// <returns></returns> protected List<ClassC> GetData() { return new List<ClassC> { new ClassC {ID = 1, Name = "Name1"}, new ClassC {ID = 2, Name = "Name2"}, new ClassC {ID = 3, Name = "Name3"}, new ClassC {ID = 4, Name = "Name4"} }; } } /// <summary> /// /// </summary> public class ClassC { /// <summary> /// Gets or sets the ID. /// </summary> /// <value>The ID.</value> public int ID { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get; set; } } }
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18