2013-11-26 134 views
1

用兩個詞我要返回上一個selecteditem而不再選擇它或不觸發SelectedIndexChanged方法。如何防止組合框SelectedIndexChanged觸發?

這是情況:我有組合框,當選擇一個項目時,datagridview填充行。您可以在datagridview中編輯內容並將其保存到文件中。如果您不保存更改並嘗試更改組合框中的項目,它會告訴您所有更改都將丟失。我製作了一個消息框,可以讓你選擇是(改變)還是不改變(不改變)。如果您點擊是,一切正常,但如果您單擊否,那麼我必須返回上一個選定的項目。當我這樣做時,我觸發SelectedIndexChanged,並使datagridview再次加載並刪除更改。這裏是我在SelectedIndexChanged方法中的代碼:

if (!ChangeMade) 
     { 
      //#1 Some Code 
     } 
else 
     { 
      DialogResult dialogResult = 
      MessageBox.Show("Are you sure you want to change the manifacturer?" + 
          "\n All the changes you have done will be lost.", 
      "Warning", MessageBoxButtons.YesNo); 

      if (dialogResult == DialogResult.Yes) 
      { 
       //same code as #1     
      } 
      else 
      { 
       //Here must be the code that returns the previous 
       //item without selecting it. 
      } 

對不起,我的英文。

回答

3

正如我所看到的,您只想在用戶更改組合框時更改數據。對於這種情況SelectionChangeCommitted是完美的,因爲只有在用戶對combobox進行更改時纔會觸發。在MSDN

+0

這顯然是一個更好的解決方案。很高興學習一些東西。謝謝! – Dethariel

+0

感謝您的回答。我嘗試你和Dethariel的答案。他們都在工作,但我認爲你更好。 – Georgi

-1
this.comboBox1.SelectedIndexChanged -= new EventHandler(comboBox1_SelectedIndexChanged); 
+0

.. ..。什麼 ??? – zey

0

我做的方式

private void TypeSelectionChangeCommitted(object sender, EventArgs e) 
{ 
    if (!ChangeMade) 
    { 
     //#1 Some Code 
    } 
    else 
    { 
     DialogResult dialogResult = 
     MessageBox.Show("Are you sure you want to change the manifacturer?" + 
         "\n All the changes you have done will be lost.", 
     "Warning", MessageBoxButtons.YesNo); 

     if (dialogResult == DialogResult.Yes) 
     { 
      //same code as #1     
     } 
     else 
     { 
      //Here must be the code that returns the previous 
      //item without selecting it. 
     } 
    } 
} 

更多信息:

private void ComboBoxOnChange(...) 
{ 
    if (!shouldTrigger) 
     return; 

    shouldTrigger = true; 
    // Here goes your code 
    should trigger = false; 
}