Automatically find the Label associated to a WebControl through the AssociatedControlID
2 min read
2 min read
private IDictionary<string, Label> associatedLabels; //1st=controlID, 2nd=Label instance
...
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
...
associatedLabels = new Dictionary<string,Label>();
FindAllLabelControls(this.Page, associatedLabels);
..
}
...
/// <summary>
/// Finds all label controls on the page that have the AssociatedControlID set and adds them
/// to the passed Dictionary <paramref name="labelCollection"/>
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="labelCollection">The label collection.</param>
private void FindAllLabelControls(Control parent, IDictionary<string, Label> labelCollection)
{
if (labelCollection == null)
throw new ArgumentNullException("The IList<Label> labelCollection is null! That cannot be!");
if (parent is Label)
{
Label lbl = parent as Label;
if (!String.IsNullOrEmpty(lbl.AssociatedControlID))
labelCollection.Add(new KeyValuePair<string, Label>(lbl.AssociatedControlID, lbl));
}
else
{
foreach (Control ctrl in parent.Controls)
{
FindAllLabelControls(ctrl, labelCollection);
}
}
}
Label lbl = null;
associatedLabels.TryGetValue(controlID, out lbl);