Find control in ListView EmptyDataTemplate

Caline picture Caline · Mar 5, 2009 · Viewed 17.5k times · Source

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>

In Page_Load() I have the following:

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.

Answer

Mcbeev picture Mcbeev · Mar 5, 2009

I believe that unless you call the DataBind method of your ListView somewhere in code behind, the ListView will never try to data bind. Then nothing will render and even the Literal control won’t 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
        }    
    }
}