views:

161

answers:

3

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

A: 

Perhaps in DataSourceChanged you could check the state of SelectedIndex, if your lucky you could then just force SelectedIndex = -1.

Reddog
+4  A: 

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;
    
Joseph Sturtevant
A: 

If you just want to clear the selected value, you can use ClearSelected after you set the DataSource. But if you dont want the event to fire, then you'll have to use one of Joseph's methods.

SwDevMan81