wilsonlego
wilsonlego

Reputation: 97

Hidden/Visible display depending on C# Dropdown selection

To be brief, I need the Textbox with ID="textComments" to only appear when the dropdown option of 'Other' is selected from the dropdown, and then disappear if another selection is made. I could do this with JS but it needs to be in C#.

<asp:DropDownList runat="server" ID="dropEnquiryType" CssClass="dropdownRequestList">
    <asp:ListItem Value="Customer Services" Text="Customer Services"></asp:ListItem>
    <asp:ListItem Value="Website" Text="Website"></asp:ListItem>
    <asp:ListItem Value="Contract" Text="Contract Hire"></asp:ListItem>
    <asp:ListItem Value="Other" Text="Other"></asp:ListItem>
</asp:DropDownList>

<asp:label runat="server" ID="lblComments" AssociatedControlID="textComments" CssClass="textLabel">Comments:</asp:label>
<asp:TextBox runat="server" MaxLength="200" TextMode="MultiLine" Columns="40" Rows="4" ID="textComments" Wrap="true" CssClass="textComments"></asp:TextBox>

And help would be greatly appreciated.

Upvotes: 0

Views: 11966

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

  • Make the DropDownList first AutoPostBack=true
  • handle it's SelectedIndexChanged-event
  • Switch visibility of both controls there

aspx:

<asp:DropDownList AutoPostBack="true" OnSelectedIndexChanged="dropEnquiryType_Changed" runat="server" ID="dropEnquiryType" CssClass="dropdownRequestList">
    <asp:ListItem Value="Customer Services" Text="Customer Services"></asp:ListItem>
    <asp:ListItem Value="Website" Text="Website"></asp:ListItem>
    <asp:ListItem Value="Contract" Text="Contract Hire"></asp:ListItem>
    <asp:ListItem Value="Other" Text="Other"></asp:ListItem>
</asp:DropDownList>

codebehind:

protected void dropEnquiryType_Changed(Object sender, EventArgs e)
{
    lblComments.Visible = dropEnquiryType.SelectedValue == "Other";
    textComments.Visible = lblComments.Visible;
}

Upvotes: 2

Adrian Wragg
Adrian Wragg

Reputation: 7401

If you absolutely have to do this within C#, then a simple check in PreRender should be sufficient:

textComments.Visible = (dropEnquiryType.SelectedValue == "Other");

This will also require you to set AutoPostback on dropEnquiryType, though, which uses ... JavaScript!

Upvotes: 1

Related Questions