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.
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.
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 propertyIf 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
Put a breakpoint in your
if (this.chkSameBAddress.Checked == true)line withinCheckedChanged eventand see it is executing and then the runtime values…