2009-06-26 204 views

回答

12

此代碼應該工作...

public Form1() 
{ 
    InitializeComponent(); 

    comboBox1.Items.AddRange(new String[] { "Item1", "Item2", "Item3" }); 
} 

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    String text = "You selected: " + comboBox1.Text; 

    BeginInvoke(new Action(() => comboBox1.Text = text)); 
} 

希望它能幫助... :)

2

設置Text屬性時,您應該將SelectedIndex屬性重置爲-1。

0

ComboBox將綁定到您指定的任何對象集合,而不僅僅是您在DropDownLists中找到的文本/值組合。

你需要做的是進入ComboBox的Items集合,找到你想要更新的項目,更新綁定到ComboBox本身的Text字段的任何屬性,然後數據綁定應該自動刷新自己與新項目。

但是,我不是100%確定你確實想修改綁定的底層數據對象,所以你可能想創建一個HashTable或其他集合作爲綁定到你的ComboBox的引用。

2

移動你改變代碼組合框事件之外:

if(some condition) 
{ 
    BeginInvoke(new Action(() => comboBox.Text = "new string")); 
} 
1

也許這將有助於如果你能解釋一下你正在試圖做什麼。我發現SelectionChangeCommitted事件對於您所描述的目的比SelectedIndexChanged更有用。除此之外,可以從SelectionChangeCommitted再次更改選定的索引(例如,如果用戶的選擇無效)。此外,從代碼更改索引再次觸發SelectedIndexChanged,而SelectionChangeCommitted僅響應用戶操作而被觸發。

+0

這對我工作,謝謝! – cchamberlain 2012-03-15 20:18:33

0

你應該使用:

的BeginInvoke(新的行動((文本) => comboBox.Text = text),「要設置的新文本」);

0

儘管它在VB中,但是關於Changing Combobox Text in the SelectedIndexChanged Event的這篇博文更詳細地介紹了爲什麼您需要使用委託作爲解決方法來更改ComoboBox文本。總之,.NET試圖阻止可能發生的無限循環,因爲當對Text屬性進行更改時,.NET將嘗試將該新值與當前項目匹配併爲您更改索引,從而觸發SelectedIndexChanged事件再次。

人們來這裏尋找一個VB實現代表的可以參考下面的代碼

'Declares a delegate sub that takes no parameters 
Delegate Sub ComboDelegate() 

'Loads form and controls 
Private Sub LoadForm(sender As System.Object, e As System.EventArgs) _ 
    Handles MyBase.Load 
    ComboBox1.Items.Add("This is okay") 
    ComboBox1.Items.Add("This is NOT okay") 
    ResetComboBox() 
End Sub 

'Handles Selected Index Changed Event for combo Box 
Private Sub ComboBoxSelectionChanged(sender As System.Object, e As System.EventArgs) _ 
    Handles ComboBox1.SelectedIndexChanged 
    'if option 2 selected, reset control back to original 
    If ComboBox1.SelectedIndex = 1 Then 
     BeginInvoke(New ComboDelegate(AddressOf ResetComboBox)) 
    End If 

End Sub 

'Exits out of ComboBox selection and displays prompt text 
Private Sub ResetComboBox() 
    With ComboBox1 
     .SelectedIndex = -1 
     .Text = "Select an option" 
     .Focus() 
    End With 
End Sub 
0

// 100%的工作

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     BeginInvoke(new Action(() => ComboBox1.Text = "Cool!"); 
} 
0

我尋找了同一個問題的解決方案。但通過處理格式事件解決它:

cbWatchPath.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.cbWatchPath_Format); 

private void cbWatchPath_Format(object sender, ListControlConvertEventArgs e) 
    { 
     e.Value = "Your text here"; 
    }