Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBox and Datasource - prevent first item from being selected

Hey. I've got the following code that populates my list box

UsersListBox.DataSource = GrpList;

However, after the box is populated, the first item in the list is selected by default and the "selected index changed" event fires. How do I prevent the item from being selected right after the list box was populated, or how do I prevent the event from firing?

Thanks

like image 993
iBiryukov Avatar asked Jun 04 '10 15:06

iBiryukov


3 Answers

To keep the event from firing, here are two options I have used in the past:

  1. Unregister the event handler while setting the 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. Create a boolean flag to ignore the event.

    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;
    
like image 76
Joseph Sturtevant Avatar answered Nov 06 '22 05:11

Joseph Sturtevant


Well, it looks like that the first element is automatically selected after ListBox.DataSource is set. Other solutions are good, but they doesn't resolve the problem. This is how I did resolve the problem:

// 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;
like image 5
Taai Avatar answered Nov 06 '22 05:11

Taai


i using the following, seems to work for me:

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;
   }
}
like image 1
Hobnob343 Avatar answered Nov 06 '22 07:11

Hobnob343