ListBox和Datasource - 阻止选择第一个项目

时间:2010-06-04 15:40:59

标签: c# winforms listbox

嘿。我有以下代码填充我的列表框

UsersListBox.DataSource = GrpList;

但是,填充此框后,默认情况下会选择列表中的第一项,并触发“选定的索引已更改”事件。如何在填充列表框后立即阻止选择项目,或者如何防止事件被触发?

由于

6 个答案:

答案 0 :(得分:21)

为了防止事件被触发,以下是我过去使用过的两个选项:

  1. 在设置DataSource时取消注册事件处理程序。

    UsersListBox.SelectedIndexChanged -= UsersListBox_SelectedIndexChanged;
    UsersListBox.DataSource = GrpList;
    UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
    UsersListBox.SelectedIndexChanged += UsersListBox_SelectedIndexChanged;
    
  2. 创建一个布尔标志来忽略该事件。

    private bool ignoreSelectedIndexChanged;
    private void UsersListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ignoreSelectedIndexChanged) return;
        ...
    }
    ...
    ignoreSelectedIndexChanged = true;
    UsersListBox.DataSource = GrpList;
    UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
    ignoreSelectedIndexChanged = false;
    

答案 1 :(得分:2)

好吧,看起来在设置ListBox.DataSource之后会自动选择第一个元素。其他解决方案很好,但它们无法解决问题。这就是我解决问题的方法:

// Get the current selection mode
SelectionMode selectionMode = yourListBox.SelectionMode;

// Set the selection mode to none
yourListBox.SelectionMode = SelectionMode.None;

// Set a new DataSource
yourListBox.DataSource = yourList;

// Set back the original selection mode
yourListBox.SelectionMode = selectionMode;

答案 2 :(得分:1)

我使用以下内容,似乎对我有用:

List<myClass> selectedItemsList = dataFromSomewhere

//Check if the selectedItemsList and listBox both contain items
if ((selectedItemsList.Count > 0) && (listBox.Items.Count > 0))
{
   //If selectedItemsList does not contain the selected item at 
   //index 0 of the listBox then deselect it
   if (!selectedItemsList.Contains(listBox.Items[0] as myClass))
   {
      //Detach the event so it is not called again when changing the selection
      //otherwise you will get a Stack Overflow Exception
      listBox.SelectedIndexChanged -= listBox_SelectedIndexChanged;
      listBox.SetSelected(0, false);
      listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
   }
}

答案 3 :(得分:0)

设置IsSynchronizedWithCurrentItem="False"SelectedIndex=-1并且每件事都适合你

答案 4 :(得分:-2)

如果您只想清除所选值,可以在设置DataSource后使用ClearSelected。但如果你不希望事件发生,那么你将不得不使用约瑟夫的一种方法。

答案 5 :(得分:-4)

也许在DataSourceChanged中你可以检查SelectedIndex的状态,如果幸运的话你可以强迫SelectedIndex = -1。