下拉列表选择的值不起作用

use*_*405 11 c# asp.net selectedvalue drop-down-menu

在我的ASP.NET项目中.我有两个下拉列表和一个复选框.选中该复选框后,所选值DropDownList1必须与选中的值相同DropDownList2.但是DropDownList1.SelectedValue没有用.

这是我的代码:

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;

    }
}
Run Code Online (Sandbox Code Playgroud)

如上例所示,如果选中chkSmaeBAddress,则所选的ddlcSCountry值必须与ddlcBCountry选定值相同.

Kaf*_*Kaf 19

你在哪里绑定数据到这些下拉列表控件?它们应该仅在页面的初始加载中绑定,如下所示.我怀疑你在每个页面加载时绑定它们,因此选择的值消失.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

其他条件是ddlcSCountry和ddlcBCountry都应该具有相同的值才能选择.否则ddlcSCountry.Items.FindByValue(ddlcBCountry.SelectedItem.Value)将为null并在尝试设置Selected属性时将引发错误

如果以上两个条件都可以,那么您的代码应该可行.

编辑抱歉,我的评论代码应该是检查下拉列表控件的绑定而不是复选框.所以它应该是

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

在你的if (this.chkSameBAddress.Checked == true)行内放一个断点,CheckedChanged event看它正在执行,然后是运行时值......