Dropdown list selected value not working

user998405 picture user998405 · May 3, 2012 · Viewed 51.3k times · Source

In my ASP.NET project. I have two dropdownlist and a checkbox. When the checkbox is checked, the selected value of DropDownList1 must be same as selcted value of the DropDownList2. But the DropDownList1.SelectedValue is not working.

Here is my code:

protected void chkSameBAddress_CheckedChanged(object sender, EventArgs e)
{
    try
    {
        if (this.chkSameBAddress.Checked == true)
        {

          this.txtcSAddress1.Text=  this.txtcBAddress1.Text;
          this.txtcSAddress2.Text = this.txtcBAddress2.Text;
          this.txtcSAddress3.Text = this.txtcBAddress3.Text;
          this.txtcSAddress4.Text = this.txtcBAddress4.Text;
          this.txtcSCity.Text = this.txtcBCity.Text;
          this.txtcSPostCode.Text = this.txtcBPostCode.Text;
          this.txtcSState.Text = this.txtcBState.Text;

          this.ddlcSCountry.Items.FindByValue(ddlcBCountry.SelectedItem.Value).Selected = true;


        }

    }
    catch (Exception ex)
    {
        logger.Error(ex.Message);
        throw;

    }
}

As seen in the example above, if chkSmaeBAddress is checked then the selected value of ddlcSCountry must be same as ddlcBCountry selected value.

Answer

Kaf picture Kaf · May 3, 2012

Where are you binding data to these dropdown list controls? They should be bound only in the initial loading of the page as follows. I suspect that you are binding them in every page load and therefore selected values disappear.

protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        //Please check if you are binding checkbox controls here. 
        //If not bring them in here
    }
}

Other condition is that both ddlcSCountry and ddlcBCountry hould have same values to be able to select. Otherwise ddlcSCountry.Items.FindByValue(ddlcBCountry.SelectedItem.Value) will be null and will throw an error when trying to set the Selected property

If both above conditions are okay, your code should work.

EDIT Sorry, my commented code should be to check binding of dropdown list controls not the checkbox. so it should be as

//Please check if you are binding both dropdown list controls here. 
//If not bind them within the if (!Page.IsPostBack)

Put a breakpoint in your if (this.chkSameBAddress.Checked == true) line within CheckedChanged event and see it is executing and then the runtime values...