Michael Hollywood
Michael Hollywood

Reputation: 269

Get the item a user unselects in a ASP CheckBoxList

I expected this to be fairly straightforward but I cannot find/figure out a simple/smart solution.

I have a CheckBoxList and it has an OnSelectedIndexChanged event. If a user selects (checks) an item in the box then the event if fired and the code behind is executed. Simple.

Now if a user unchecks a box I need to do some work in the background but the problem is that when the user then deselects an item in the list it fires the event but in the code benind the event the list retains no pointer to which item the user just deselected. I find this strange and think I must be missing something obvious though various searches have yielded nothing concrete.

I guess i could maintain a list in the code behind of the items checked and everytime the event is fired figure out what has been deleted but this seems overkill if there is a simpler solution.

Thanks, Michael

Upvotes: 3

Views: 1300

Answers (1)

Imran Rizvi
Imran Rizvi

Reputation: 7438

Yes , there is no stright way to find the uncheck item not even by casting sender

Following is a tricky code that give you the index of item causing event to fire

protected void checkboxlist_SelectedIndexChanged(object sender, EventArgs e)
{
        CheckBoxList list = (CheckBoxList)sender;
        string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
        int idx = control.Length - 1;
        string sel = list.Items[Int32.Parse(control[idx])].Value;  
}

Once you get the index you can select the item and write your code.

Upvotes: 4

Related Questions