Search code examples
c#asp.netlistviewitemtemplate

How to find table cell in asp.net using c#


I want to hide an itemtemplate's data in listview using the td visibility property. Once I click a button it should show the data again that's within the itemtemplate. However, I cannot find the td control using c# in the code behind. Is there a way to find this control or another way to handle this?

 <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
  <asp:Button ID="Button1" runat="server" Text="Search" OnClick="ButtonClick" />
 <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">

     <asp:View ID="View1" runat="server">
        <asp:ListView ID="SectionListView" runat="server" InsertItemPosition="FirstItem" OnPagePropertiesChanged="SectionListView_PagePropertiesChanged">

             <ItemTemplate>
                 <tr style="">
                        <td></td>
                        <td id="row1" style="visibility:hidden;" runat="server">
                                <asp:Label ID="SectionItemLabel" runat="server" Text='<%# Eval("SectionItem") %>' />
                        </td>
                 </tr>
             </ItemTemplate>

Here is part of the code for the button click:

protected void ButtonClick(object sender, EventArgs e)
    {
        var temp = (System.Web.UI.HtmlControls.HtmlTableCell)Page.Master.FindControl("MainContent").FindControl("row1");
    }

Solution

  • You have a couple of issues. First, when you try to find "row1" within "MainContent", if won't find it because "row1" is actually a child of other children of "MainContent". It won't find them recursively unless you tell them to.

    Second, since each ListViewItem within your ListView contains "row1", they are each given their own unique ID, such as SectionListView_ctrl0_row1, SectionListView_ctrl1_row1, etc. Because of this, you need to use FindControl() on each ListViewItem.

    But, because you need to do it on each ListViewItem and because each ListViewItem contains "row1", each row will get the same property (i.e. all visible or all invisible). Here is how that could be done:

    protected void ButtonClick(object sender, EventArgs e)
    {
        foreach (ListViewItem lvi in SectionListView.Items)
        {
            if (lvi.ItemType == ListViewItemType.DataItem)
            {
                HtmlTableCell row1 = (HtmlTableCell)lvi.FindControl("row1");
                row1.Style.Add("visibility", "hidden");
            }
        }
    }
    

    If you need to style each cell individually, they would each need to be named differently. It is common to attach some sort of number or database ID to the end of the ID if that is the case.