views:

2720

answers:

1

I have the a ListView like this

<asp:ListView ID="ListView1" runat="server">
   <EmptyDataTemplate>
      <asp:Literal ID="Literal1" runat="server" text="some text"/>
   </EmptyDataTemplate>
   ...
</asp:ListView>

on my Page_Load event I have the following code

   Literal x = (Literal)ListView1.FindControl("Literal1");
   x.Text = "other text";

but x returns null. I'd like to change the text of the Literal Control but I don't have no idea how to do it.

+3  A: 

I believe that unless you call the databind method of your listview somewhere in codebehind the listview will never try to data bind and then nothing will render and even the literal control wont be created.

In your Page_Load event try something like

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //ListView1.DataSource = ...
            ListView1.DataBind();

            //if you know its empty empty data template is the first parent control
            // aka Controls[0]
            Control c = ListView1.Controls[0].FindControl("Literal1");
            if (c != null)
            {
                //this will atleast tell you  if the control exists or not
            }



        }
    }
Mcbeev
+1 - this is exactly what I needed too. Thanks!
jsidnell
Is there any way to do this in the databound method? I'd rather *not* hardcode "controls[0]" as that's sloppy.
Broam