Hi KatieNgoc,
Refer below sample.
HTML
<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Namespaces
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
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)
{
dt.Rows[i].Delete();
}
}
Session["ListItems"] = dt;
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Text";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
If Session("ListItems") Is Nothing Then
Dim dt As DataTable = DropDownItems()
DropDownList1.DataSource = dt
DropDownList1.DataTextField = "Text"
DropDownList1.DataValueField = "Value"
DropDownList1.DataBind()
Session("ListItems") = dt
End If
End If
End Sub
Private Function DropDownItems() As DataTable
Dim dt As DataTable = 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
End Function
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As DataTable = TryCast(Session("ListItems"), DataTable)
Dim liCol As ListItemCollection = DropDownList1.Items
For i As Integer = 0 To dt.Rows.Count - 1
Dim li As ListItem = liCol(i)
If li.Selected Then
dt.Rows(i).Delete()
End If
Next
Session("ListItems") = dt
DropDownList1.DataSource = dt
DropDownList1.DataTextField = "Text"
DropDownList1.DataValueField = "Value"
DropDownList1.DataBind()
End Sub
Sreenshot