Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a control inside a the LayoutTemplate of a ListView

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?

like image 806
craigmoliver Avatar asked Jan 11 '09 22:01

craigmoliver


3 Answers

Try this:

((Literal)lv.FindControl("litControlTitle")).Text = "Your text";
like image 141
tanathos Avatar answered Oct 05 '22 08:10

tanathos


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";
}
like image 30
Vindberg Avatar answered Oct 05 '22 06:10

Vindberg


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...";
}
like image 21
JonH Avatar answered Oct 05 '22 06:10

JonH