views:

625

answers:

3

I try to set like this:

ListBox lb = new ListBox();
/* Bind datas */
lb.SelectedItem = someObject;

lb truely selected the someObject item. But it would select the 1st item at first. And that motion cause SelectedIndexChanged event which I don't wanted.

I just want SelectedIndexChanged be called when someObject selected. How could I do to fix this?

A: 

don't add the selectedIndexChanged event until after you have changed the selectedItem to someObject ?

remove the event out of the form editor, or the designer.cs, and add it yourself manually by using the same code it auto generates?

matt
+3  A: 

Use a flag on the form/control to disable the event when you don't want it to fire.

public class Form1 : Form
{
    private bool itemsLoading;

    public Form1()
    {
        InitializeComponent();
        LoadListItems();
    }

    private void LoadListItems()
    {
        itemsLoading = true;
        try
        {
            listBox1.DataSource = ...
            listBox1.SelectedItem = ...
        }
        finally
        {
            itemsLoading = false;
        }
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (itemsLoading)
            return;

        // Handle the changed event here...
    }
}
Aaronaught
This is cool solution!Thank you!
Jennal
A: 

I am for the solution of matt. Sometimes it may be just better to add and/or remove event handlers at right time; otherwise, a lot of messy flags will have to be added.

bill