views:

83

answers:

2

I have a Winforms App in C# with a ListView control. This ListView shows a list of TO-DO items and I am using the 'ItemSelectionChanged' event to handle updates.

The problem is that the 'ItemSelectionChanged' event fires twice each time I try to make an update.

The ItemSelectionChanged event refreshs the form to represent the updates (ie remove item from list).

Is there a way to disable the event from firing after the refresh?

UPDATE1:

private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {   
        if (e.IsSelected)
        {                
            listView1.Items[e.ItemIndex].Remove();

            listView1.SelectedIndices.Clear();
            listView1.Focus();

            listView1.Update();
        }
        else
        {

        }

    }
+1  A: 

Yes just remove the EventHandler at the start of the refresh and add it again after it has finished refreshing

i.e

// Remove handler
listView1.ItemSelectionChanged -= new ListViewItemSelectionChangedEventHandler(listView1_ItemSelectionChanged);

// Do refresh

// Add again
listView1.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(listView1_ItemSelectionChanged);
w69rdy
Do I need any additional references for the 'OnSelectionChanged'?
John M
No, You just need to replace ListView with the name of your ListViewControl i.e. ListView1 and MethodName should be the name of the function that is called when the OnSelectionChanged event is fired i.e. ListView1_OnSelectionChanged where ListView1 is again the name of your ListViewControl
w69rdy
For me the 'OnSelectionChanged' doesn't show up in Intellisense.
John M
I had it slightly off, I've updated the example to make it clearer. You just need to replace listView1 with the name of your listview and the same for listView1_ItemSelectionChanged. Let me know if you get stuck
w69rdy
It should go in the refresh method, the remove at the start and the add at the bottom. If that doesnt work post the code and I'll take a look for you
w69rdy
+1  A: 

Yes, it will fire twice. Once because the previously selected item became unselected, again for the newly selected item. You just have to make sure you see the selection event:

    private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) {
        if (e.IsSelected) {
            // Update form
            //...
        }
    }
Hans Passant
@Hans - thanks but the IsSelected didn't work for me. There must be something else about my code that keeps it firing twice.
John M
No, it will definitely fire twice. This is by design. The point is to detect the one that you are interested in. Which isn't that clear from your question.
Hans Passant