C# 如何在 comboBox.SelectedIndexChanged 事件中更改 comboBox.Text?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1049775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:00:08  来源:igfitidea点击:

How do I Change comboBox.Text inside a comboBox.SelectedIndexChanged event?

c#comboboxselectedindexchanged

提问by McBainUK

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?

我的问题是组合框文本始终显示所选索引的字符串值而不是新字符串。这是一种方法吗?

采纳答案by Daniel Pryden

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... :)

希望它有帮助... :)

回答by Martin Robins

You should reset the SelectedIndexproperty to -1 when setting the Textproperty.

设置SelectedIndex属性时,您应该将属性重置为 -1 Text

回答by Dillie-O

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

ComboBox 将绑定到您指定的任何对象集合,而不是简单地具有您在 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.

您需要做的是进入 ComboBox 的 Items 集合,找到您要更新的项目,更新您绑定到 ComboBox 本身的 Text 字段的任何属性,然后数据绑定应自动使用新项目刷新自身.

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.

但是,我不是 100% 确定您实际上想要修改正在绑定的基础数据对象,因此您可能想要创建一个 HashTable 或其他一些集合作为绑定到您的 ComboBox 的引用。

回答by arbiter

Move your change code outside of combobox event:

将更改代码移到组合框事件之外:

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

回答by Daniel Pryden

Perhaps it would help if you could explain exactly what you're trying to do. I find that the SelectionChangeCommitted event is considerably more useful for purposes like what you describe than SelectedIndexChanged. Among other things, it's possible to change the selected index again from SelectionChangeCommitted (e.g. if the user's selection is invalid). Also, changing the index from code fires SelectedIndexChanged again, whereas SelectionChangeCommitted is only fired in response to user actions.

如果你能准确地解释你想要做什么,也许会有所帮助。我发现 SelectionChangeCommitted 事件对于您描述的目的比 SelectedIndexChanged 有用得多。除此之外,还可以从 SelectionChangeCommitted 再次更改所选索引(例如,如果用户的选择无效)。此外,更改代码中的索引会再次触发 SelectedIndexChanged,而 SelectionChangeCommitted 仅在响应用户操作时触发。

回答by Jerzy Gebler

you should use:

你应该使用:

BeginInvoke(new Action((text) => comboBox.Text = text), "new text to set");

BeginInvoke(new Action((text) => comboBox.Text = text), "要设置的新文本");

回答by KyleMit

Although it's in VB, this blogpost on Changing Combobox Text in the SelectedIndexChangedEventgoes 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.

尽管它在 VB 中,但这篇关于SelectedIndexChanged事件中更改组合框文本的博客文章更详细地说明了为什么需要使用委托作为更改 ComoboBox 文本的解决方法。简而言之,.NET 正在尝试防止可能发生的无限循环,因为当 Text 属性发生更改时,.NET 将尝试将该新值与当前项匹配并为您更改索引,从而触发 SelectedIndexChanged 事件再次。

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

来这里寻找Delegates的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

回答by user2853852

//100% worked

//100%有效

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

回答by Kiryl

I searching for solution for same issue. But solve it by handling Format event:

我正在寻找相同问题的解决方案。但是通过处理 Format 事件来解决它:

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

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