【发布时间】:2016-07-18 10:33:47
【问题描述】:
我有一个组合框,我使用 SelectIndexChanged 事件来捕获用户和编程更改。
清除并重新加载绑定到组合框的列表将自然触发索引为 -1 的事件处理程序。
然后用 selectedindex=-1
combobox1.SelectedIndex = 0 ; // will NOT fire the event.
但是
combobox1.SelectedIndex = 1 ; // or higher number WILL fire the event.
在这两种情况下,我都在以编程方式更改 selextedindex 并期望触发事件。
我以简单的形式验证了该行为。
namespace cmbTest
{
public partial class Form1 : Form
{
private BindingList<string> items = new BindingList<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = items;
loadItems();
}
private void loadItems()
{
items.Add("chair");
items.Add("table");
items.Add("coffemug");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Fired with selected item index:" + comboBox1.SelectedIndex);
}
private void button1_Click(object sender, EventArgs e)
{
int index = comboBox1.SelectedIndex;
// Clear and reload items for whatever reason.
items.Clear();
loadItems();
// try select old item index; if it doesnt exists, leave it.
try { comboBox1.SelectedIndex = index; }
catch { }
}
}
}
表单有一个combobox1 和一个button1。
为清楚起见进行编辑(我希望):
- 运行程序
- 选择“椅子”。消息“使用选定的项目索引触发:0”
- 点击按钮。消息“使用选定的项目索引触发:-1”
- 选择“表格”。消息“使用选定的项目索引触发:1”
- 点击按钮。消息“使用选定的项目索引触发:-1”和 “使用选定的项目索引:1 触发”。
我希望在选择“椅子”时点击按钮时收到两条消息,因为我以编程方式将索引更改为 0。
那么,为什么这没有像我预期的那样工作,什么是可接受的解决方法?
【问题讨论】:
-
吞下异常?这不好。检查是否有异常被抛出。
-
指的是catch{}?仅当重新加载列表不再具有项目 inde 时,才会使用 try 语句。这里不是这种情况,本例不需要
-
我在您的代码中看不到
comboBox1.SelectedIndex = 0;。问题到底出在哪里? -
当您运行程序并选择索引 0(椅子)然后按下按钮。再次选择索引 0 时不会触发事件。
-
我无法真正重现您的问题。您能具体说明导致此问题的具体步骤吗?