Show/Hide Group of Controls in ASP.Net using C#
In ASP.Net it is mostly required to show or hide a group of controls placed on a web form. The checkbox web server control is most commonly used to toggle the visible state of each control when required. As we know each web server control in ASP.Net has a Visible property that accepts a Boolean value as true or false and enables to get or set the visibility of the associated control on the rendered web page.
It is very simple to show or hide a single control using checkbox control by changing the value of Visible property of the target control but what if we want to hide a set of controls. The first thought comes in mind that how to change the state of each control by setting their Visible property to false and toggle it to true when required. This thought makes it a bit complex but in ASP.Net we have a solution to manage the show/hide behavior for a set of controls.
In ASP.Net we have a Panel web server control that serves a container for multiple child controls. You can place your set of controls which belong to a same group inside a Panel control as shown in the HTML code below:
<asp:Panel ID="Panel1" runat="server">
<table>
<tr>
<th colspan="2">
Login here..
</th>
</tr>
<tr>
<td>
<asp:Label ID="lblUserName"
runat="server"
Text="Username: ">
</asp:Label>
</td>
<td>
<asp:TextBox ID="txtUserName"
runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblPassword"
runat="server"
Text="Password: ">
</asp:Label>
</td>
<td>
<asp:TextBox ID="txtPassword"
runat="server">
</asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
The Panel control will render as a HTML div element on the web form that can be accessed from the server side C# code. You can use the checkbox control to show/hide the set of controls placed inside the Panel control by simply changing the value of Visible property of the Panel control only. HTML Code for ASP.Net checkbox control used in this example:
<asp:CheckBox ID="chkShowHide"
runat="server"
Text="Show/Hide"
AutoPostBack="true"
OnCheckedChanged="chkShowHide_CheckedChanged" />
The Server side C# code used to handle the Visible property associated the Panel control container to show or hide the group of server controls:
protected void Page_Load(object sender, EventArgs e)
{
chkShowHide_CheckedChanged(sender, e);
}
protected void chkShowHide_CheckedChanged(object sender, EventArgs e)
{
if (chkShowHide.Checked)
Panel1.Visible = true;
else
Panel1.Visible = false;
}
In the above C# code we have used the OnCheckedChanged event handler of CheckBox control to change the visible state of the target Panel control. We have also called the event handler code at Page_Load event of the web page so that the Panel control appears in the default hidden state at page load and performs according to the checked or unchecked state of the associated CheckBox control.

* will not be published
* hint: http://www.example.com