代码示例:
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(some condition)
{
comboBox.Text = "new string"
}
}
我的问题是组合框文本始终显示所选索引的字符串值,而不是新字符串。这是一种方法吗?
代码示例:
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(some condition)
{
comboBox.Text = "new string"
}
}
我的问题是组合框文本始终显示所选索引的字符串值,而不是新字符串。这是一种方法吗?
这段代码应该可以工作...
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));
}
希望它有帮助... :)
设置属性时应将属性重置SelectedIndex
为 -1 Text
。
将您的更改代码移到组合框事件之外:
if(some condition)
{
BeginInvoke(new Action(() => comboBox.Text = "new string"));
}
如果你能准确地解释你想要做什么,也许会有所帮助。我发现 SelectionChangeCommitted 事件对于您所描述的目的比 SelectedIndexChanged 更有用。除其他外,可以从 SelectionChangeCommitted 再次更改所选索引(例如,如果用户的选择无效)。此外,从代码更改索引会再次触发 SelectedIndexChanged,而 SelectionChangeCommitted 仅在响应用户操作时触发。
简而言之,.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
进一步阅读:请参阅这篇关于在SelectedIndexChanged
事件中更改组合框文本的帖子(我的),其中更详细地说明了为什么需要使用委托作为解决方法来更改组合框文本。
//100% 工作
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
BeginInvoke(new Action(() => ComboBox1.Text = "Cool!");
}
ComboBox 将绑定到您指定的任何对象集合,而不是简单地具有您在 DropDownLists 中找到的文本/值组合。
您需要做的是进入 ComboBox 的 Items 集合,找到您要更新的项目,更新您绑定到 ComboBox 本身的 Text 字段的任何属性,然后数据绑定应该使用新项目自动刷新自身.
但是,我不能 100% 确定您是否真的想要修改被绑定的底层数据对象,因此您可能想要创建一个 HashTable 或其他一些集合作为绑定到您的 ComboBox 的引用。
你应该使用:
BeginInvoke(new Action((text) => comboBox.Text = text), "要设置的新文本");
我正在寻找相同问题的解决方案。但是通过处理 Format 事件来解决它:
cbWatchPath.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.cbWatchPath_Format);
private void cbWatchPath_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = "Your text here";
}