Search code examples
c#asp.net

Hide and Show Label and Button


I have 2 labels and 2 text boxes and 1 buttons displayed.

When the page loads the Name and Button (will be initially displayed). Later when i click on the Button i need to display the age label and textbox. How can i do this ?

<ol>
     <li>
          <asp:Label runat="server" AssociatedControlID="Name">
             User name
          </asp:Label>
          <asp:TextBox runat="server" ID="Name" Width="167px" />
          <asp:Button ID="Button1" runat="server" Text="Button" />
     </li>                           
     <li>
          <asp:Label runat="server" AssociatedControlID="age">age</asp:Label>
          <asp:TextBox runat="server" ID="age" TextMode="age" Width="240px" />
     </li>                         
</ol>

code for button press

protected void Button1_Click(object sender, EventArgs e)
{

}

Solution

  • You could set the label/textbox Visible property to True in server side. Alternatively, you could use JavaScript to avoid post backs to the server.

    Add OnClientClick to your button :

    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ShowLabel();"/>
    

    and declare the JavaScript function on page:

    <script type="text/javascript">
        function ShowLabel() {
          // Note that the client ID might be different from the server side ID
          document.getElementById('lblAge').style.display = 'inherit';
        }
    </script>
    

    You need to set the Label Display style to none initially.

    <asp:Label ID="lblAge" style="display: none;" runat="server" AssociatedControlID="age">age</asp:Label>