2012-05-03 28 views
11

在我的ASP.NET项目中。我有两个dropdownlist和一个复选框。当复选框被选中时,选定的值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; 

    } 
} 

如在上面的例子中看到的那样,如果chkSmaeBAddress检查然后选定值ddlcSCountry必须相同ddlcBCountry选择的值。

+0

ddlcSCountry.SelectedIndex = ddlcSCountry.Items.IndexOf(ddlcSCountry.Items.FindByValue(ddlcBCountry.SelectedItem.Value)) – Nalaka526

+0

你能扩大**不工作**(显然因为你贴),你得到任何错误?是下降poulated? – V4Vendetta

+0

我不知道什么错误。下拉列表没有得到回应 – user998405

回答

18

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

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 
    } 
} 

其他条件是ddlcSCountry和ddlcBCountry都应该有相同的值才能选择。否则ddlcSCountry.Items.FindByValue(ddlcBCountry.SelectedItem.Value)将为空,并且在尝试设置Selected属性时会抛出错误

如果上述两个条件均可用,则您的代码应该可以工作。

编辑对不起,我评论的代码应该是检查下拉列表控件的绑定而不是复选框。所以应该为

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

将断点在if (this.chkSameBAddress.Checked == true)线内CheckedChanged event,看看它正在执行,然后运行值...

+0

你好。我使用实体数据源绑定下拉列表 – user998405

+0

您可以像上面所述那样放置一个断点并检查运行时值。你的代码没有问题,但我怀疑问题在于你完成它的顺序。你的'chkSameBAddress_CheckedChanged'事件是否触发? – Kaf

+0

ya。我尝试在chkSameBAddress_CheckedChanged中放置一个断点。 CheckedChanged事件被触发 – user998405

0

尝试此选择

ddlcSCountry.Text=ddlcBCountry.SelectedItem.Value; 

将选择需要的项目

+0

嗨,没有ddlcSCountry.text。它是ddlcSCountry.SelectedItem.text? – user998405

+0

from Upper letter“Text” – Likurg

+0

@ user998405我编辑 – Likurg

0

请确保chkSameBAddress.AutoPostBack设置为true。如果已设置但仍然无效,请考虑使用UpdatePanel控件或使用JavaScript将该逻辑移动到客户端。

+0

ya。我已经设置为真 – user998405

2

当然,你正在试图使下拉框相等?

使用

ddlcSCountry.SelectedIndex = ddlcSCountry.FindStringExact(ddlcBCountry.Text); 

这将在列表中选择相应的选项,而不是仅仅设置在现场,当你有你的文本选项潜在的价值观,这是非常有用的文本。

0

请确保您拥有的AutoPostBack设置为true的属性DropDownList。

2

可接受的解决方案是最常见原因的明显解决方案,但是,还有一个更令人惊讶的问题会导致此问题!

我的列表值来自一个数据库,并且这些值有来自数据库值的换行和回车:\r\n。这些值看起来像一个无辜的空间,但实际上他们不是!

我的解决方案是去除这些隐藏的Char值。希望能帮助到你。