I am stuck on this issue and cannot seem to find a way around it. I have a CheckBoxList control. If you did not know, the FindControl() method on the CheckBoxList control returns "this". Microsoft did it because internally they dont create many ListItem objects but just one. Anyway, I am trying to find out if a posted back control is one of the controls in my CheckBoxList. My code looks something along the lines of:
if (!(System.Web.UI.ScriptManager.GetCurrent(Page) == null)) {
string postbackControlId = System.Web.UI.ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (!string.IsNullOrEmpty(postbackControlId))
{
Control control = ControlFinder.RecursiveFindChildControl(Controls, postbackControlId);
if (!(control == null))
{ }
}
}
Is there anyway to enumerate the child controls of a CheckBoxList or find if an ID that I have is equal to one of theirs?
Thanks, Mike
The UniqueID
of a CheckBox
within a CheckBoxList
is the UniqueID
of the CheckBoxList
plus a $
plus the index of the item, so you can check whether postbackControlId
is one of the CheckBox
controls like this:
if (postbackControlId.StartsWith(this.checkBoxList.UniqueID + "$"))
{
int itemIndex = Convert.ToInt32(
postbackControlId.Substring(this.checkBoxList.UniqueID.Length + 1), 10);
// ...
}
If you're only looking to find out whether the postback was caused by one of the items in the CheckBoxList
, you don't need to traverse the entire control hierarchy. You don't even need to drill down into the list. Something like this should work fine:
string elementID = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (elementID.Contains(chkList.UniqueID))
{
//one of the checkboxes caused the postback
}