Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an item to a drop down list in ASP.NET?

I want to add the "Add new" at a specific index, but I am not sure of the syntax. I have the following code:

protected void Page_Load(object sender, EventArgs e) {         DRPFill();         if (!IsPostBack)         {             DropDownList1.Items.Add("Add New");         } } public void DRPFill() {     if (!IsPostBack)     {         //Object         AddMajor objMajor = new AddMajor();          //Data Table         DataTable dtMajor = objMajor.find();          //Data Source         DropDownList1.DataSource = dtMajor;         DropDownList1.DataValueField = "MajorID";         DropDownList1.DataTextField = "MajorName";          //Data Bind         DropDownList1.DataBind();     } } 
like image 353
Scorps Avatar asked Jul 04 '13 11:07

Scorps


People also ask

How do I add an item to a select list?

SelectList list = new SelectList(repository. func. ToList()); ListItem li = new ListItem(value, value); list. items.

What is selected value in DropDownList?

Cause SelectedValue will give you the value stored for current selected item in your dropdown and SelectedItem. Value will be Value of the currently selected item.


2 Answers

Try this, it will insert the list item at index 0;

DropDownList1.Items.Insert(0, new ListItem("Add New", "")); 
like image 96
Ben Gulapa Avatar answered Sep 23 '22 03:09

Ben Gulapa


Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">      <asp:ListItem Text="Add New" Value="0" /> </asp:DropDownList> 

If you want to add it at a different index, maybe the last then try:

ListItem lst = new ListItem ( "Add New" , "0" );  DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst); 
like image 33
Full Time Skeleton Avatar answered Sep 20 '22 03:09

Full Time Skeleton