2009-01-11 75 views
24

如何訪問ListView控件的LayoutTemplate中的控件?我需要litControlTitle並設置其Text屬性。訪問ListView的LayoutTemplate中的控件

<asp:ListView ID="lv" runat="server"> 
    <LayoutTemplate> 
    <asp:Literal ID="litControlTitle" runat="server" /> 
    <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> 
    </LayoutTemplate> 
    <ItemTemplate> 
    </ItemTemplate> 
</asp:ListView> 

有什麼想法?也許通過OnLayoutCreated事件?

回答

36

試試這個:

((Literal)lv.FindControl("litControlTitle")).Text = "Your text"; 
+0

我最初嘗試過,但沒有奏效。然後我來到了這裏。雖然謝謝! – craigmoliver 2009-01-11 22:57:48

+3

很奇怪......我把這段代碼放在OnLayoutCreated的回調裏面,當我綁定ListView時它工作正常...... – tanathos 2009-01-11 23:08:52

18

完整的解決方案:

<asp:ListView ID="lv" OnLayoutCreated="OnLayoutCreated" runat="server"> 
    <LayoutTemplate> 
    <asp:Literal ID="lt_Title" runat="server" /> 
    <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> 
    </LayoutTemplate> 
    <ItemTemplate> 
    </ItemTemplate> 
</asp:ListView> 

在代碼隱藏:

protected void OnLayoutCreated(object sender, EventArgs e) 
{ 
    (lv.FindControl("lt_Title") as Literal).Text = "Your text"; 
} 
3

這種技術適用於模板佈局;使用控制的init事件:

<asp:ListView ID="lv" runat="server" OnDataBound="lv_DataBound"> 
    <LayoutTemplate> 
    <asp:Literal ID="litControlTitle" runat="server" OnInit="litControlTitle_Init" /> 
    <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> 
    </LayoutTemplate> 
    <ItemTemplate> 
    </ItemTemplate> 
</asp:ListView> 

和捕獲到的控制的參考以用於在ListView的DataBound事件代碼隱藏(例如):

private Literal litControlTitle; 

protected void litControlTitle_Init(object sender, EventArgs e) 
{ 
    litControlTitle = (Literal) sender; 
} 

protected void lv_DataBound(object sender, EventArgs e) 
{ 
    litControlTitle.Text = "Title..."; 
} 
0

對於嵌套LV循環:

void lvSecondLevel_LayoutCreated(object sender, EventArgs e) 
{ 
    Literal litText = lvFirstLevel.FindControl("lvSecondLevel").FindControl("litText") as Literal; 
    litMainMenuText.Text = "This is test"; 
} 
相關問題