2008-10-22 51 views
3

我有一個組合控件,它將一個TextBox和一個Label控件添加到它的Controls集合中。當我嘗試將標籤的AssociatedControlID設置爲文本框的ClientID時,出現此錯誤在標籤上設置AssociatedControlID失敗

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

好吧,有點背景。我得到了這個主複合控件,它動態地爲其控件集合添加了許多「元素」。其中一個元素碰巧是這個'MatrixTextBox',它是由TextBox和Label組成的控件。

我保持標籤和文本框爲受保護的類變量,並在CreateChildControls中初始化它們:

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

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

我嘗試添加控件以Controls集合,甚至後設置

ElementLabel.AssociatedControlID = ElementTextBox.ClientID; 

都是正確的在PreRender中 - 都會產生相同的錯誤。我究竟做錯了什麼?

回答

7

我想你一定不能使用ElementTextBox的ClientID屬性,而是ID。 ClientID是您必須在Javascript中使用的頁面唯一ID,例如在document.getElementyById,是不一樣的服務器端ID - 特別是如果你有控制等

一個母版和/或控制所以應該​​是:

ElementLabel.AssociatedControlID = ElementTextBox.ID; 

希望這有助於。

+0

謝謝!該死的我現在感到很蠢:) – 2008-10-22 08:08:49

+0

@Hojou:哦,...類似的錯誤一直髮生在我身上。很明顯,如果你看到解決方案... – splattne 2008-10-22 08:15:56

3

可能有助於該遇到的錯誤其他讀者:

請注意,設置AssociatedControlID也失敗了,如果你沒有明確地首先設置輸入控件的ID相關聯,在運行時輸入控件的標籤。這是一個需要注意的問題,如果您要動態創建多個文本框,複選框或帶有標籤的radiobuttions。

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