[英]C# Combobox Selected.Index = -1 not working
It should reset the Combobox to no value, Combobox is in the same panel, but the code sets the index to 0 wich is the first value of the data binded list. 它应该将Combobox重置为无值,Combobox位于同一面板中,但是代码将索引设置为0,这是数据绑定列表的第一个值。 It works on the second click tho...ON the first click it sets the index to 0, on the second to -1.
它可以在第二次单击时起作用,在第一次单击时将索引设置为0,第二次将索引设置为-1。
if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
{
foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
{
if(C.SelectedIndex != -1)
{
C.SelectedIndex = -1;
}
}
}
Perhaps you could try adding a dummy first item to your ComboBox to act as a placeholder. 也许您可以尝试将虚拟的第一项添加到ComboBox中以充当占位符。
This way you can deselect simply using ComboBox.SelectedIndex = 0;
这样,您可以简单地使用
ComboBox.SelectedIndex = 0;
取消选择ComboBox.SelectedIndex = 0;
Just be sure not to interpret this item in the ComboBox as a real item anywhere. 只是要确保不要在任何地方将ComboBox中的该项解释为真实项。
Also, try: 另外,请尝试:
ComboBox.ResetText();
ComboBox.SelectedIndex = -1;
Or: 要么:
ComboBox.SelectedItem = null;
thanks all for answers...in the end I solved the issue with a workaround. 谢谢大家的回答...最后,我通过解决方法解决了这个问题。 The problem was, that button of the code above needed two clicks to set index to -1.
问题是,上面代码的按钮需要单击两次才能将索引设置为-1。 On the first click it moved to 0 and on the second to -1.
第一次单击时,它将移至0,第二次单击时将移至-1。 I dont know why tho...Another problem was i had a index changed event on combobox and i wanted to fire it only once - not twice.
我不知道为什么...另一个问题是我在组合框上发生了索引更改事件,我只想触发一次,而不是两次。 I solved the problem this way...
我这样解决了问题...
if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
{
foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
{
if(C.SelectedIndex != -1)
{
C.SelectedIndexChanged -= this.ComboBox_Promo_SelectedIndexChanged;
while (C.SelectedIndex != -1)
{
C.SelectedIndex = -1;
}
C.SelectedIndexChanged += this.ComboBox_Promo_SelectedIndexChanged;
this.ComboBox_Promo_SelectedIndexChanged(C, EventArgs.Empty);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.