23

如何访问控件中的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>

有什么想法吗?也许通过OnLayoutCreated事件?

4

5 回答 5

35

试试这个:

((Literal)lv.FindControl("litControlTitle")).Text = "Your text";
于 2009-01-11T22:37:27.820 回答
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>

在代码隐藏中:

protected void OnLayoutCreated(object sender, EventArgs e)
{
    (lv.FindControl("lt_Title") as Literal).Text = "Your text";
}
于 2010-05-20T10:02:57.260 回答
4

这种技术适用于模板布局;使用控件的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...";
}
于 2012-02-20T22:53:34.303 回答
0

对于嵌套 LV 回路:

void lvSecondLevel_LayoutCreated(object sender, EventArgs e)
{
    Literal litText = lvFirstLevel.FindControl("lvSecondLevel").FindControl("litText") as Literal;
    litMainMenuText.Text = "This is test";
}
于 2013-09-04T13:32:25.537 回答
0

如果你需要 VB 版本,这里是

Dim litControl = CType(lv.FindControl("litControlTitle"), Literal)
litControl.Text = "your text"
于 2018-10-20T05:10:13.190 回答