[英]How do I Change comboBox.Text inside a comboBox.SelectedIndexChanged event?
代码示例:
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));
}
希望它有帮助... :)
设置Text
属性时,您应该将SelectedIndex
属性重置为 -1。
将更改代码移到组合框事件之外:
if(some condition)
{
BeginInvoke(new Action(() => comboBox.Text = "new string"));
}
如果你能准确地解释你想要做什么,也许会有所帮助。 我发现 SelectionChangeCommitted 事件对于您描述的目的比 SelectedIndexChanged 有用得多。 除此之外,还可以从 SelectionChangeCommitted 再次更改所选索引(例如,如果用户的选择无效)。 此外,更改代码中的索引会再次触发 SelectedIndexChanged,而 SelectionChangeCommitted 仅在响应用户操作时触发。
简而言之,.NET 正在努力防止可能发生的无限循环。 当 Text 属性发生更改时,.NET 将尝试将该新值与当前项匹配并为您更改索引,从而再次触发 SelectedIndexChanged 事件。
来这里寻找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
进一步阅读:请参阅有关在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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.