Automatically find the Label associated to a WebControl through the AssociatedControlID

ASP.net Label controls own the property "AssociatedControlID" which points to the control to which the label is associated. This property will then be rendered as "for" attribute on the final HTML.  This property is however one-way only: it's easy to find the associated control at runtime but there is no way to have a control, say a TextBox, and to find it's associated label (if any). There are however situations where you'd like to get this kind of information. Just to mention one: think of a custom TextBox control which, its visibility property is set to false at runtime, automatically also hides it's associated label. This is just a "dummy scenario" but it has some realistic elements.

Since I recently faced a similar situation I implemented a way for reaching the associated label of a WebControl. The idea is to collect all of the Label controls within a certain container (i.e. UserControl, Page, Panel etc...) and to use a Dictionary for creating the link between label and associated control. See the code example below.

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);
}
}
}

Now, finding the label is easy...
Label lbl = null;
associatedLabels.TryGetValue(controlID, out lbl);

Note, the "FindAllLabelControls" method is recursive and may pose some performance degradation, although it shouldn't be that much if you choose the "parent" argument wisely :)
Kindle

Comments

0

Your ad here?