Fire ListView.SelectedIndexChanged Event Programmatically?

How to programmatically fire the SelectedIndexChanged event in a ListView?

I decided that the first item in my ListView will automatically become selected after the user performs a specific action. Code already exists in the SelectedIndexChanged event to highlight the selected item. The item is not only not highlighted, but the breakpoint set in SelectedIndexChanged never hits. Moreover, Debug.WriteLine cannot execute the output, so I am sure that the event has not been fired.

The following code does not fire an event:

listView.Items[0].Selected = false; listView.Items[0].Selected = true; listView.Select(); Application.DoEvents(); 

An additional call to the .Select () method was included for good measure .;) Cancel (.Selected = false) was included to deselect the ListViewItem in the .Items collection, if it might have been selected by default, and therefore setting it to "true" will not affect. The call to "Application.DoEvents ()" is another last ditch method.

Should this code not raise the SelectedIndexChanged event?

I should mention that the SelectedIndexChanged event fires properly when an item is selected from the keyboard or mouse.

+4
source share
3 answers

Canceling it by setting it to false will not trigger the event, but setting it to true.

  public Form1 () { InitializeComponent(); listView1.Items[0].Selected = false; // Doesn't fire listView1.Items[0].Selected = true; // Does fire. } private void listView1_SelectedIndexChanged (object sender, EventArgs e) { // code to run } 

You may have something else. What event do you use for your selection code?

+2
source

Why can't you move the code that is currently inside your event handler method to a method that can be called from the source, as well as from your code?

Something like that:

 class Foo { void bar(Object o, EventArgs e) { // imagine this is something important int x = 2; } void baz() { // you want to call bar() here ideally } } 

will be reorganized into this:

 class Foo { void bar(Object o, EventArgs e) { bop(); } void baz() { bop(); } void bop() { // imagine this is something important int x = 2; } } 
+2
source

If you create a class derived from ListView , you can call the protected method OnSelectedIndexChanged . This will trigger the SelectedIndexChanged event.

+2
source

All Articles