In this article, we will learn how to show/hide a textbox based on the user’s selection of a drop-down list. Let’s say, you have a simple form that asks from the user if he likes to read fiction books. If he chooses yes from the drop-down list, a text box will appear so he can enter his favorite book’s name.

Sound simple. Right?

Show/Hide TextBox C# based on DropDownList value

So let’s start with the HTML code.

HTML

    <form id="form1" runat="server">
        Do you like to read fiction? 
         <asp:DropDownList
             ID="ddlFiction"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="ddlFiction_SelectedIndexChanged">

             <asp:ListItem
                 Text="No. I don’t like fiction"
                 Value="N">
             </asp:ListItem>
             <asp:ListItem
                 Text="Yes. I love to read fiction"
                 Value="Y">
             </asp:ListItem>

         </asp:DropDownList>

    </form>

So far, we have a form with a drop-down menu. The drop-down has two options to choose from.

Now, add a panel control and hide it by setting its visible property to false.

        <asp:Panel
            ID="pnlfictionbook" runat="server" Visible="false">
            Your favorite book is: 
    <asp:TextBox
        ID="txtBook"
        runat="server">
    </asp:TextBox>

        </asp:Panel>
Note: It’s important to set the PRoperty AutoPostBack of the DropDownList to True.

C#

Every time the user selects an option from the DropDownList, the Event ddlFiction_SelectedIndexChanged will be executed. inside the Event function, we check the value of the selected DropDownListe Item. If the value is ‘Y’ the visibility property of the PAnel, which contains the TextBox, is set to true.

        protected void ddlFiction_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlFiction.SelectedItem.Value == "Y")
            {
                pnlfictionbook.Visible = true;
            }
            else
            {
                pnlfictionbook.Visible = false;
            }

        }

Happy Coding!

Related Articles

 

Last modified: September 10, 2019

Comments

Write a Reply or Comment

Your email address will not be published.