views:

2405

answers:

4

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

I need to get to litControlTitle and set it's 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?

+7  A: 

Try this:

((Literal)lv.FindControl("litControlTitle")).Text = "Your text";
tanathos
I tried that initially, but that didn't work. Then I came here. Thanks though!
craigmoliver
very strange... I place this code inside the callback of OnLayoutCreated, and when I bind the ListView it works fine...
tanathos
oh, well I didn't put it in that event, trying now
craigmoliver
that worked, thanks!
craigmoliver
+3  A: 

I tried tanathos' answer:

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

inside OnLayoutCreated, and it worked for me. Thanks!

Note that using OnDataBinding attribute in your control will NOT work if it is inside the LayoutTemplate part of ListView.

( I just don't have enough reputation to reply to the thread nor to vote up, so here.)

azure_ardee
+2  A: 

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";
}
Anders Vindberg
A: 

FYI, this doesn't work if you're trying to find a control in the layouttemplate of a nested listview...

kenyee