Products
Services
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: (2092)
Favorites:

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.

Example:
In file dropdownTest.aspx

 Code Snippet 1

<%@ Control Language="c#" AutoEventWireup="false"
 Codebehind="dropdownTest.aspx.cs"   
TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>

<html>
<head>
<title>DropDownList Control in C#</title>
</head>
<body>
<!-- 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>
</asp:dropdownlist></td>
</body>
</html>


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");

        ddl.Items.Add(newItem);

      }            
    }
  }
}


See other Scripts in Web controls

Submit Your Scripts:


System Message:
  • Your C# script has been sent. Please allow 48 hours for processing.


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

[ Refresh Image ]