Monthly Archives: 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));
}

Index of an Item of a ListView

When you are working with a GridView, it is usually pretty easy to ascertain the index for a particular row inside an event handler for that row e.g. in an event handler for the RowCreated event, the row-index for the row which was just created is e.Row.RowIndex. The GridViewRowEventArgs serves it right up!

With a ListView, you need to burn a few more calories to get that number. The ListViewItemEventArgs does not contain the index. So, in an event handler for the ItemCreated event, you can get the index for that item with the following statement:

int index = ((System.Web.UI.WebControls.ListViewDataItem)e.Item).DataItemIndex;

You cast the item (which is a ListViewItem) to the ListViewDataItem type. That type has a Property called DataItemIndex.

Not really so hard after all.