views:

629

answers:

2

I have a composite control that adds a TextBox and a Label control to its Controls collection. When i try to set the Label's AssociatedControlID to the ClientID of the Textbox i get this error

Unable to find control with id 
'ctl00_MainContentPlaceholder_MatrixSetControl_mec50_tb'
that is associated with the Label 'lb'.

Ok so a little background. I got this main-composite control that dynamically adds a number of 'elements' to its control collection. One of these elements happen to be this 'MatrixTextBox' which is the control consisting of a TextBox and a Label.

I hold the Label and TextBox as protected class variables and init them in CreateChildControls:

    ElementTextBox = new TextBox();
    ElementTextBox.ID = "tb";
    Controls.Add(ElementTextBox);

    ElementLabel = new Label();
    ElementLabel.ID = "lb";
    Controls.Add(ElementLabel);

I tried setting the

ElementLabel.AssociatedControlID = ElementTextBox.ClientID;

both right after adding the controls to the Controls collection and even in PreRender - both yield the same error. What am i doing wrong?

+4  A: 

I think you mustn't use the ClientID property of the ElementTextBox, but the ID. ClientID is the page-unique ID you'd have to use in Javascript, e.g. in the document.getElementyById and is not the same as the server-side ID - especially if you have a masterpage and/or controls in controls etc.

So it should be:

ElementLabel.AssociatedControlID = ElementTextBox.ID;

Hope this helps.

splattne
Thanks! Damn i feel stupid now :)
Per Hornshøj-Schierbeck
@Hojou: oh, ... similar mistakes happen to me all the time. It is so clear if you see the solution...
splattne
Excellent find.
Floetic
+1  A: 

Possibly helpful to other readers that encounter the error:

Note that setting AssociatedControlID fails too if you're associating the label with an input control at runtime without explicitly setting the ID of the input control first. This is an issue that requires attention if you are creating multiple textboxes, checkboxes or radiobuttions with labels dynamically.

private void AddRadioButton(PlaceHolder placeholder, string groupname, string text)
{
    RadioButton radio = new RadioButton();
    radio.GroupName = groupname;
    radio.ID = Guid.NewGuid().ToString(); // Always set an ID.

    Label label = new Label();
    label.Text = text;
    label.AssociatedControlID = radio.ID;

    placeholder.Controls.Add(radio);
    placeholder.Controls.Add(label);
}
Patrick de Kleijn