2017-03-17 37 views
2

我是c#的新手,現在我正在學習如何基於某些表單動作觸發事件。C#Winforms:基於選定的項目在組合框中設置文本

這是視圖部分:

private void comboGoodsName_TextChanged(object sender, EventArgs e) 
{ 
    controller.selectName(comboGoodsName.Text); 
} 

public void nameChanged(object sender, MeasurementEventArgs e) 
{ 
    comboGoodsName.TextChanged -= comboGoodsName_TextChanged; 
    comboGoodsName.Text = e.value; 
    comboGoodsName.TextChanged += comboGoodsName_TextChanged; 
} 

這是控制器的一部分:

public void selectName(string name) 
{   
    model.Name = name.Split('|')[0].Trim(); 

    if (name.Contains(" | ")) 
    { 
     string code = name.Split('|')[1].Trim(); 
     model.NameCode = code; 
    } 
} 

的情況如下:
我想有它的一些項ComboBox (無關緊要的是什麼)。項目是以下格式的名稱和代碼的組合:NAME | CODE。當我在ComboBox(鍵入它)中輸入一些文本時,將觸發comboGoodsName_TextChanged,而該comboGoodsName_TextChanged又調用selectName,該值設置模型的屬性,這反過來引發了nameChanged觀察到的事件。如預期的那樣,此工作正常(將NAME置於ComboBoxCODETextBox - 未顯示爲不相關)。從ComboBox下拉列表中選擇項目時出現問題。當我選擇項目時,而不是在ComboBox中顯示NAME,而是顯示NAME | CODE

編輯:在模型中,屬性設置正確,我通過打印它的值來確認。因此,問題僅與在ComboBox中顯示正確的值有關。

+0

試圖瞭解你的需求。你是否曾希望用戶在組合框中看到CODE?如果不是爲什麼不爲** **代碼使用ComboBox屬性* DisplayMember *而爲**代碼**使用* ValueMember? –

+0

是的,我希望它被顯示,所以用戶可以區分不同的項目。而且,當用戶選擇一個項目時,一條信息會轉到組合框,另一條轉到文本框。 – Fejs

+0

什麼觸發** nameChanged()**? –

回答

1

試試這個:

private void comboGoodsName_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    // if combobox has selected item then continue 
    if (comboGoodsName.SelectedIndex > -1) 
    { 
     // split the selecteditem text on the pipe into a string array then pull the first element in the array i.e. NAME 
     string nameOnly = comboGoodsName.GetItemText(this.comboGoodsName.SelectedItem).Split('|')[0]; 

     // handing off the reset of the combobox selected value to a delegate method - using methodinvoker on the forms main thread is an efficient to do this 
     // see https://msdn.microsoft.com/en-us/library/system.windows.forms.methodinvoker(v=vs.110).aspx 
     this.BeginInvoke((MethodInvoker)delegate { this.comboGoodsName.Text = nameOnly; }); 
    }  
} 
+0

因爲我是新手,你能解釋一下這是幹什麼的嗎?順便說一句,它現在正在按預期工作。 – Fejs

+0

增加了對代碼的評論 - 希望有所幫助! –

相關問題