How do I Change comboBox.Text inside a comboBox.Se

2019-05-11 13:41发布

Code example:

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if(some condition)
    {
        comboBox.Text = "new string"
    }
}

My problem is that the comboBox text always shows the selected index's string value and not the new string. Is the a way round this?

9条回答
你好瞎i
2楼-- · 2019-05-11 14:34

A ComboBox will bind to whatever object collection you specify, as opposed to simply having a text/value combination that you find in DropDownLists.

What you'll need to do is go into the ComboBox's Items collection, find the item you want to update, update whatever property you have being bound to the Text field in the ComboBox itself and then the databinding should automatically refresh itself with the new item.

However, I'm not 100% sure you actually want to modify the underlying data object being bound, so you may want to create a HashTable or some other collection as a reference to bind to your ComboBox instead.

查看更多
▲ chillily
3楼-- · 2019-05-11 14:34

Although it's in VB, this blogpost on Changing Combobox Text in the SelectedIndexChanged Event goes into a little more detail as to why you need to use a delegate as a workaround to change the ComoboBox Text. In short, .NET is trying to prevent an endless loop that could occur because when a change to the Text property occurs, .NET will try to match that new value to the current items and change the index for you, thereby firing the SelectedIndexChanged event again.

People coming here looking for a VB implementation of Delegates can refer to the code below

'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
查看更多
等我变得足够好
4楼-- · 2019-05-11 14:39

This code should work...

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

Hope it helps... :)

查看更多
登录 后发表回答