Contact Us

Scripts: C# :: Web Controls :: Library Article #2

Developer's Section

Adding and Removing Items From DropDownList in C#
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (3535)

Learn how to dinamycally add or remove items from a DropDownList WebControl in C#

In the following explanation you will learn how to add and delete items from a dropDownList in C#. We will use a simple class that will call the addDeleteItems on the onLoad event of the DropDownList. Finally We will set it to run at server so that the code is executed by the server.

In file dropdownTest.aspx

 Code Snippet 1

<%@ Control Language="c#" AutoEventWireup="false"
TargetSchema="" %>

<title>DropDownList Control in C#</title>
<!-- create a drop down and assign the onload event to addDeleteItems-->
<asp:dropdownlist id="DropDownList1" Width="152px"
 OnLoad="addDeleteItems" runat="server">
  <asp:ListItem Value="Item 1 Value" Selected="True">Item 1</asp:ListItem>
  <asp:ListItem Value="Item 2 Value">Item 2</asp:ListItem>

Now, In file dropdownTest.aspx.cs
 Code Snippet 2

namespace test_project
  using System;
  using System.Data;
  using System.Web;
  using System.Web.UI.WebControls;
  using System.Web.UI.HtmlControls;

  public class test_dropdown
    protected System.Web.UI.WebControls.DropDownList DropDownList1;

    private void Page_Load(object sender, System.EventArgs e)
           //Set any methods on page load here

    //create the addDeleteItems that adds and delete items (called on onLoad).
    //from the dropdown dynamicaly
    protected void addDeleteItems(object sender, System.EventArgs e) 
      DropDownList ddl = (DropDownList)sender;

      ListItem thisItem1 = (ListItem)ddl.Items.FindByValue("Item 1 Value");
      ListItem thisItem2 = (ListItem)ddl.Items.FindByValue("Item 2 Value");

      if( thisItem1 != null && thisItem2 != null) {

        ddl.Items.Remove(thisItem1); //remove an item from dropdown

        ListItem newItem = new ListItem("Item 3 Value","Item 3");



See other Scripts in Web Controls

Submit Your Scripts:

If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]