asp.net CheckBoxList: how to remove list item programmatically
CheckBoxListRemoveItem.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckBoxListRemoveItem.aspx.cs" Inherits="CheckBoxListRemoveItem" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>asp.net CheckBoxList: how to remove list item programmatically</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">CheckBoxList: Remove List Item</h2>
<asp:Label
ID="Label1"
runat="server"
>
</asp:Label>
<br /><br />
<asp:CheckBoxList
ID="CheckBoxList1"
runat="server"
RepeatColumns="3"
BorderColor="Blue"
BorderWidth="2"
BackColor="DodgerBlue"
ForeColor="Snow"
>
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Orange</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>White</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button
ID="Button1"
runat="server"
Font-Bold="true"
ForeColor="DarkBlue"
Text="Remove Selected Item(s)"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
CheckBoxListRemoveItem.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CheckBoxListRemoveItem : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Label1.ForeColor = System.Drawing.Color.OrangeRed;
Label1.Font.Bold = true;
}
}
protected void Button1_Click(object sender, EventArgs e) {
Label1.Text = "Items removed:";
ArrayList ListItems = new ArrayList();
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected == true)
{
ListItems.Add(li.Text.ToString());
}
}
for (int i = 0; i < ListItems.Count; i++)
{
string currentItem =(string) ListItems[i];
ListItem li = new ListItem();
li.Text = currentItem;
CheckBoxList1.Items.Remove(li);
Label1.Text += " " + currentItem;
}
}
}
- asp.net RangeValidator: how to validate date range
- asp.net CheckBoxList: how to add list item programmatically
- asp.net BulletedList: how to add list item programmatically
- asp.net SqlCommand() example: how to build SQL dynamically
- asp.net Dictionary, Key, Value example: using System.Collections.Generic
- asp.net DataBind() example: data binding with control properties
- asp.net single value data binding example: using variable
- asp.net QueryStringParameter example: using SelectParameters
- asp.net ControlParameter example: using SqlDataSource
- How to change Button control Style, ForeColor, BackColor programmatically in asp.net