Search code examples
c#asp.netgridviewhtml-listsfindcontrol

C# GridView FindControl HTML unordered list


I want to find an unordered list inside my GridView so that I can hide it based on a condition. I do not know what to cast the object as however. Using HtmlGenericControl does not seem to work. I receive a Object reference not set to an instance of an object error.

Markup:

<asp:GridView ID="myGV" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="myCb" runat="server" Text='Hi'/>
                <ul id="myUnorderedList" runat="server" Visible="True">
                    <li>
                        <asp:TextBox ID="myTb" runat="server" Width="300" />
                    </li>
                </ul>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

C#:

foreach (GridViewRow row in myGV.Rows)
{
    if (Some Condition)
    {
        //works bc properly casted to CheckBox
        ((CheckBox) row.FindControl("myCb")).Visible = false; 

        //Does not work. What to cast this to?
        ((System.Web.UI.HtmlControls.HtmlGenericControl) row.FindControl("myUnorderedList")).Visible = false;
    }
}

Solution

  • System.Web.UI.HtmlControls.HtmlGenericControl is a correct cast for ul.

    Besides, you do not even need to cast to HtmlGenericControl, because Visible is a property of System.Web.UI.Control from which all web controls inherited.

    You just need the following code -

    (row.FindControl("myUnorderedList")).Visible = false;