Remove Item from DropDownList on Button Click using C# in ASP.Net

Last Reply 9 days ago By KatieNgoc

Posted 10 days ago

Hello,

In a list of items in dropdown list box. 

How can I implement each time I select the item, view it, click on agree check box, click on next button, then this item will remove in a list?

 

Posted 9 days ago

HTML

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropdownListSession._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>

C#

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace DropdownListSession
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!this.IsPostBack)
            {
                if (Session["ListItems"] == null)
                {
                    DataTable dt = DropDownItems();
                    DropDownList1.DataSource = dt;
                    DropDownList1.DataTextField = "Text";
                    DropDownList1.DataValueField = "Value";
                    DropDownList1.DataBind();
                    Session["ListItems"] = dt;
                }
            }
        }
 
        private DataTable DropDownItems()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Text");
            dt.Columns.Add("Value");
            dt.Rows.Add("Item1", "1");
            dt.Rows.Add("Item2", "2");
            dt.Rows.Add("Item3", "3");
            dt.Rows.Add("Item4", "4");
            return dt;
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable dt = Session["ListItems"] as DataTable;
            ListItemCollection liCol = DropDownList1.Items;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ListItem li = liCol[i];
                if (li.Selected)
                {
                    Response.Redirect("Next.aspx");
                    dt.Rows[i].Delete();
                }
            }
            Session["ListItem"] = dt;
            DropDownList1.DataSource = dt;
            DropDownList1.DataTextField = "Text";
            DropDownList1.DataValueField = "Value";
            DropDownList1.DataBind();
        }
    }
}

Thank you.