【问题标题】:Setting AssociatedControlID on label fails在标签上设置 AssociatedControlID 失败
【发布时间】:2008-10-22 06:27:10
【问题描述】:

我有一个复合控件,它将一个 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 中,两者都产生相同的错误。我做错了什么?

【问题讨论】:

    标签: asp.net composite-controls


    【解决方案1】:

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

    应该是这样的:

    ElementLabel.AssociatedControlID = ElementTextBox.ID;
    

    希望这会有所帮助。

    【讨论】:

    • @Hojou:哦,......类似的错误一直发生在我身上。如果你看到解决方案就很清楚了......
    • 另一点是确保在创建初始控件时以编程方式设置 ID,否则它是匿名创建的,并且关联的控件永远无法连接到它。对于第一次尝试这个的人来说可能并不明显。 :)
    【解决方案2】:

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

    请注意,如果您在运行时将标签与输入控件相关联,而没有先明确设置输入控件的 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);
    }
    

    【讨论】:

    • 谢谢!这正是我面临的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多