2012-05-03 29 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值。希望能幫助到你。