3

我有一个复合控件,它将一个 TextBox 和一个 Label 控件添加到它的 Controls 集合中。当我尝试将标签的 AssociatedControlID 设置为文本框的 ClientID 时,我收到此错误

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

好的,有一点背景。我得到了这个主复合控件,它动态地将许多“元素”添加到它的控件集合中。其中一个元素恰好是这个“MatrixTextBox”,它是由一个文本框和一个标签组成的控件。

我将 Label 和 TextBox 作为受保护的类变量,并在 CreateChildControls 中初始化它们:

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

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

我尝试设置

ElementLabel.AssociatedControlID = ElementTextBox.ClientID;

在将控件添加到 Controls 集合之后,甚至在 PreRender 中,两者都产生相同的错误。我究竟做错了什么?

4

2 回答 2

7

我认为您不能使用ElementTextBox 的 ClientID 属性,而是使用ID。ClientID 是您必须在 Javascript 中使用的页面唯一 ID,例如在 document.getElementyById 中,并且与服务器端 ID 不同 - 特别是如果您有母版页和/或控件等中的控件。

所以应该是:

ElementLabel.AssociatedControlID = ElementTextBox.ID;

希望这可以帮助。

于 2008-10-22T06:55:23.367 回答
3

可能对遇到错误的其他读者有帮助:

请注意,如果您在运行时将标签与输入控件相关联,而没有先明确设置输入控件的 ID,则设置 AssociatedControlID 也会失败。如果您要动态创建多个带有标签的文本框、复选框或单选按钮,这是一个需要注意的问题。

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);
}
于 2008-11-15T17:30:22.247 回答