Search code examples
asp.netvb.netaspx-user-control

How to Close a Panel control on a Page from a Control in a UserControl on that Page


I'm trying to close a Panel control in an ASP.NET web page by clicking a LinkButton that is in a User Control that is on that same page. I've tried the solutions found on this site and others and cannot get any to work.

Any ideas?

Code example below.

Main Page. It has a User Control which contains Label Button. I want to click the Label button and close the Panel.

Page HTML:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="default.aspx.vb" Inherits="_default" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Sample Page</title>
</head>
<body>
    <form id="form1" runat="server" class="container-fluid">
        <UserControl:Header runat="server" />

        <asp:Panel ID="Panel1" runat="server"></asp:Panel>
    </form>
</body>
</html>

Page Code Behind:
Partial Class _default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
End Class

User Control. I want to click the "LinkButton1" object in the User Control, and then hide the "Panel1" object in the Page.

User Control HTML:
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="header.ascx.vb" Inherits="shared_usercontrols_header" %>

<asp:LinkButton ID="LinkButton1" runat="server">My Link Button</asp:LinkButton>


User Control Code Behind:
Partial Class _default
    Inherits System.Web.UI.Page

    Private Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
        Panel1.Visible = False
    End Sub
End Class

Solution

  • Well, if you directly use the control object and name, then that is resolved at compile time.

    But, we don't know ahead of time that you may, or may not have a Panel1 on that page.

    So, you have to "look for" the panel on the page.

    Hence, this should work:

    Protected Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
    
    
        Dim MyPanel As Panel = Page.FindControl("Panel1")
    
        MyPanel.Visible = False
    
    
    End Sub