ARATHY
ARATHY

Reputation: 349

adding option to drop down list

I have a drop down list with multiple values. I have a list item named "Other". When selecting other I want to generate a text box with required field validator. I have written like this:

Markup:

<asp:DropDownList ID="dl_test_name" runat="server" 
                  OnSelectedIndexChanged="SelectedIndexChanged" 
                  Height="22px" Width="103px">
    <asp:ListItem>Science</asp:ListItem>
    <asp:ListItem>Maths</asp:ListItem>          
    <asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="tb_other" runat="server" Width="94px" Visible="False">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" 
                            ControlToValidate="tb_other" ErrorMessage="*">   
</asp:RequiredFieldValidator>

Code-behind:

protected void SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList dropDownList = (DropDownList)sender;
    if (dropDownList.SelectedValue == "Other")
    {
        tb_other.Enabled = true;
        tb_other.Text = string.Empty;
        tb_other.Visible = true;
    }
    else
    {
        tb_other.Enabled = false;
        tb_other.Text = dropDownList.SelectedValue;
    }
}

but when selecting on any list item ,control doesn't go to SelectectedIndexChanged event. Only after reloading the page does it work.

What is the problem?

Upvotes: 2

Views: 119

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34844

To make your DropDownList post back to the server you need to use the AutoPostback property, like this:

<asp:DropDownList ID="dl_test_name" runat="server" 
                  OnSelectedIndexChanged="SelectedIndexChanged" 
                  Height="22px" Width="103px" AutoPostBack="true">

Upvotes: 4

Ankur
Ankur

Reputation: 1021

Arathy, make AutopostBack property of dropdown to true in aspx

Upvotes: 3

Related Questions