Daily Archives: 25 June 2009

Find the CheckBox that Fired the AutoPostBack in a CheckBoxList

Scenario: you have a CheckBoxList and you have set AutoPostBack to true. You go to handle the SelectIndexChanged event for that CheckBoxList and realise that there is no “built-in” way to figure out which CheckBox was selected/deselected by the user. That is, the good old EventArgs has not been overridden such that an EventArgs object has a property which identifies the relevant CheckBox.

There is actually a very easy way to address this. As you can see from the following screen capture, on a PostBack, the UniqueID of the CheckBoxList is suffixed with a dollar sign and then a number:


The number is the index of the relevant CheckBox in the Items collection of the CheckBoxList. And so, as an example, here is some code which handles an AutoPostBack event by a CheckboxList:

protected void CheckBoxListRoles_SelectedIndexChanged(object sender, EventArgs e)
{
	int itemIdx = GetPostBackItemIndex(this);
	ListItem itemPosted = CheckBoxListRoles.Items[itemIdx];

	switch(itemPosted.Selected)
	{
		case true: Roles.AddUserToRole(userName, itemPosted.Value); break;
		default: Roles.RemoveUserFromRole(userName, itemPosted.Value); break;
	}

}

public int GetPostBackItemIndex(Page page)
{
	string ctrlname = page.Request.Params.Get("__EVENTTARGET");
	return int.Parse(ctrlname.Substring(ctrlname.Length - 1, 1));
}