JJ.
JJ.

Reputation: 9950

How do I populate a dropdownlist based on a selection from another dropdownlist?

protected void ddlEnvironment_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlEnvironment.SelectedIndex == 0)
    {
        ddlServers.Items.Add("item1");
    }

    if (ddlEnvironment.SelectedIndex == 1)
    {
        ddlServers.Items.Add("item2");
    }

    if (ddlEnvironment.Text == "Production")
    {
    }
}

The above is not working. When I make a selection on ddlEnvironment and it is the first item on the list (index 0), the other dropdownlist is not upading with "item1". Why?

Upvotes: 0

Views: 1342

Answers (2)

Adil
Adil

Reputation: 148110

There could be different reasons by default dropdown list do no do postback.

  • Check if you have AutoPostBack="true"
  • You bind the ddlEnvironment in !Page.IsPostBack block so that it maintains its state on postback

    if(!Page.IsPostBack)
    {
       ddlEnvironment.AuutoPostBack = true;
       ddlEnvironment.DataSource = datasource; 
       ddlEnvironment.DataBind();
    }
    

Upvotes: 2

egrunin
egrunin

Reputation: 25053

I assume you have AutoPostBack=true - right?

If you're initializing ddlEnvironment in your Page_Load() event handler, it's being reset on postback.

You need to do something like this:

If (!Page.IsPostback)
{ 
    // initialize ddlEnvironment here 
}

Upvotes: 0

Related Questions