I used the following sample code to try to get it done:
Markup :
<asp:CheckBoxList ID="CheckBoxList1" AutoPostBack="true" runat="server"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem item1 = new ListItem("1", "1");
ListItem item2 = new ListItem("2", "2");
ListItem item3 = new ListItem("3", "3");
CheckBoxList1.Items.Add(item1);
CheckBoxList1.Items.Add(item2);
CheckBoxList1.Items.Add(item3);
}
}
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBoxList1.SelectedItem != null)
{
if (CheckBoxList1.SelectedItem.Selected)
Response.Write("You checked " + CheckBoxList1.SelectedItem.Text);
else
Response.Write("You unchecked " + CheckBoxList1.SelectedItem.Text);
}
}
The
SelectedIndexChanged
event is fired in both cases (Check box
check
and
uncheck
) and, Asp.net can give you the correct selected item in the
CheckBoxList
when you "
check
" one (I found one case however it was failing to show the correct check box). But, unfortunately, when you "
uncheck
" a check box, it can't give you the information because the "
CheckBoxList1.SelectedItem
" is null and there is no other suitable property to get this information.
So, you have to do some client side scripting (Using
JQuery
or
JavaScripts
) to get the checked or unchecked check box reference, store or send this information to codebehind and then execute the server side code with that information.