Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find control in ListView EmptyDataTemplate

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.

like image 525
Caline Avatar asked Mar 05 '09 01:03

Caline


2 Answers

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
        }    
    }
}
like image 139
Mcbeev Avatar answered Sep 18 '22 10:09

Mcbeev


You can use the following:

 protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.EmptyItem)
            {
                 Control c = e.Item.FindControl("Literal1");
                if (c != null)
                {
                    //this will atleast tell you  if the control exists or not
                }
            }
        }
like image 42
avani gadhai Avatar answered Sep 20 '22 10:09

avani gadhai