访问ListView的LayoutTemplate内的控件

cra*_*ver 24 c# asp.net listview asp.net-3.5

如何访问在一个控制LayoutTemplate一个的ListView控制?

我需要进入litControlTitle并设置其Text属性.

<asp:ListView ID="lv" runat="server">
  <LayoutTemplate>
    <asp:Literal ID="litControlTitle" runat="server" />
    <asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
  </LayoutTemplate>
  <ItemTemplate>
  </ItemTemplate>
</asp:ListView>
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?也许是通过OnLayoutCreated活动?

tan*_*hos 35

试试这个:

((Literal)lv.FindControl("litControlTitle")).Text = "Your text";
Run Code Online (Sandbox Code Playgroud)

  • 对于阅读此答案的任何人,请确保在`ListView`绑定到源之后调用`FindControl`(即,在ListView上调用`DataBind`之后).否则,当您查找控件时,ListView的布局模板将不会准备就绪,因此`FindControl`将不会成功. (8认同)
  • 非常奇怪...我把这个代码放在OnLayoutCreated的回调中,当我绑定ListView时它工作得很好...... (3认同)

Vin*_*erg 17

完整的解决方案:

<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>
Run Code Online (Sandbox Code Playgroud)

在codebehind中:

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