Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

c# - How to prevent ListBox.SelectedIndexChanged event?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...