是否可以刷新组合框的项目并保留所选项目,以便不会触发SelectedIndexChanged
事件?即使所选项目不在新项目列表中?
以下代码似乎会重置所选项目并触发SelectedIndexChanged
事件。
void RefreshComboboxItems()
{
var ds = GetRefreshedItems();
cb.DataSource = ds;
cb.DisplayMember = "Name";
cb.ValueMember = "Value";
}
// cb is already initialized and an item is selected
RefreshComboboxItems(); // Want to keep the selected item unchanged and don't trigger the event
答案 0 :(得分:2)
不,您可以获取当前的SelectedValue,删除事件处理程序,刷新组合,尝试再次使用保存的值设置SelectedValue,然后读取事件处理程序
void RefreshComboboxItems()
{
try
{
int currentValue = -1;
if(cb.SelectedValue != null)
currentValue = Convert.ToInt32(cb.SelectedValue);
cb.SelectedIndexChanged -= mySelectedIndexChangedMethod;
var ds = GetRefreshedItems();
cb.DataSource = ds;
cb.DisplayMember = "Name";
cb.ValueMember = "Value";
if(currentValue != -1)
cb.SelectedValue = currentValue;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cb.SelectedIndexChanged += mySelectedIndexChangedMethod;
}
}
请注意,我已经在finally中读取了事件处理程序,以确保事件处理程序被重新读入组合框,以防异常导致在删除事件处理程序后过早退出此代码
答案 1 :(得分:0)
如果您想暂时删除事件处理程序,可以执行以下操作:
void RefreshComboboxItems()
{
cb.SelectedIndexChanged -= Ddl_SelectedIndexChanged;
var ds = GetRefreshedItems();
cb.DataSource = ds;
cb.DisplayMember = "Name";
cb.ValueMember = "Value";
cb.SelectedIndexChanged += Ddl_SelectedIndexChanged;
}