下拉列表更改时,Combobox将SelectedIndex重置为零

时间:2014-08-07 16:20:38

标签: c# winforms combobox

我有一个绑定到数据源的组合框。并且在keypress事件上更新数据源,以便combobox.Items.count是可变的,有时变为零。 每次组合框被下拉或关闭时,combobox.selectedindex被重置为零,如果项目计数也为零,则会导致ArgumentOutOfRange异常。 如何防止组合框下拉或关闭下拉列表中的selectedindex更改?

这是放在按键事件处理程序中的代码的一部分:

DataRow[] rows = AllProfilesTable2.Select(string.Format("FullName LIKE '%{0}%'", strFindStr));
DataTable filteredTable = AllProfilesTable2.Clone();
foreach (DataRow r in rows)
  filteredTable.ImportRow(r);

cb.DataSource = null;
cb.DataSource = filteredTable.DefaultView;
cb.DisplayMember = "FullName";
cb.ValueMember = "ID";
if (cb.Items.Count > 0) {
  cb.DroppedDown = true;
  cb.SelectedIndex = -1;
  cb.Text = strFindStr;
  cb.SelectionStart = strFindStr.Length;
}
else {
  cb.DroppedDown = true;
  cb.SelectedIndex = -1;
  cb.Text = strFindStr;
  cb.SelectionStart = strFindStr.Length;
}

1 个答案:

答案 0 :(得分:0)

您可以在绑定之前检查绑定源是否有效。 ComboBox有一个DropDownClosed事件,该事件在菜单关闭时发生。你可以从这里操纵它。 我假设在没有选择任何项目的情况下关闭菜单时会发生重置问题。

MSDN说:

  

要取消选择当前选定的项目,请将SelectedIndex设置为-1。如果项是数据绑定项,则无法将ComboBox项的SelectedIndex设置为-1。

来源:MSDN - ComboBox Class

相关问题