Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using a listbox in my C#2.0 windows forms application. The method to populate the list box is

    private void PopulateListBox(ListBox lb, ReportColumnList reportColumnList)
    {
        lb.DataSource = reportColumnList.ReportColumns;
        lb.DisplayMember = "ColumnName";
        lb.ValueMember = "ColumnName";
    }

However, when it executes the method it also calls the SelectedIndexChanged event handler of the listbox, even though I am not setting the selected index in the method above. How can I prevent the SelectedIndexChanged event handler from being called for the above code?

I want the event to be called only when the user makes the selections in the ListBox. Or is there any other event which is only for user selecting listbox items using mouse click?

On another note, even if the user clicks on an empty area in the list box the SelectedIndexChanged event gets fired. So I am wondering how different is it from the MouseClick event?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
637 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are three ways you can go about this.

A) Don't hook into the SelectedIndexChanged event until AFTER you've called this method.

B) Have a private boolean in your class that's initially set to true. At the start of your PopulateListBoxmethod, set it to false, and at the end set it back to true. In your event handler for SelectedIndexChanged , if the flag is false, just return and do nothing.

C) In the start of your PopulateListBoxmethod, unhook from the event (this.listbox1.SelectedIndexChanged -= myMethod;) and then right before the method is done, rehook into that event.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...