Access a control inside a the LayoutTemplate of a ListView

♀尐吖头ヾ 提交于 2019-12-18 04:29:15

问题


How do I access a Control in the LayoutTemplate of a ListView control?

I need to get to litControlTitle and set its Text attribute.

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

Any thoughts? Perhaps via the OnLayoutCreated event?


回答1:


Try this:

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



回答2:


The complete solution:

<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>

In codebehind:

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



回答3:


This technique works for template layout; use the init event of the control:

<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>

And capture a reference to the control for use in the code-behind (e.g) in the ListView's DataBound event:

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...";
}



回答4:


For Nested LV Loop:

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



回答5:


In case you need the VB version, here it is

Dim litControl = CType(lv.FindControl("litControlTitle"), Literal)
litControl.Text = "your text"


来源:https://stackoverflow.com/questions/433846/access-a-control-inside-a-the-layouttemplate-of-a-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!