-2

H,

I have a listView with an event set to ItemChecked, now i need to do something like:

var tmp = this.listView.ItemChecked;
this.listView.ItemChecked = null; //set the event to null

// run some code which checkes some item in the list
// wehre the event shouldnt get fired on

this.listView.ItemChecked = tmp; //set the event again

Problem is that i can not read the event, i get the message that it can be used only on the left side of a statement.

Any Ideas?

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • Can't you just unsubscribe all handlers, cache them in a local list, then re-subscribe them afterwards? – Chris Nov 13 '12 at 13:40
  • Check out the following answer [How to remove all event handlers from a control](http://stackoverflow.com/a/5475424/519383). – juan.facorro Nov 13 '12 at 13:44
  • @juan.facorro that only works if it's *your* event. See the accepted answer on that question. – Jon B Nov 13 '12 at 13:47

4 Answers4

1
this.listView.ItemChecked -= myEventHandler;

// run some code

this.listView.ItemChecked += myEventHandler;
Cole Cameron
  • 2,213
  • 1
  • 13
  • 12
1

You can unsubscribe and resubscribe to do what you're trying to do:

private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    listView1.ItemChecked -= new ItemCheckedEventHandler(listView1_ItemChecked);

    // do stuff

    listView1.ItemChecked += new ItemCheckedEventHandler(listView1_ItemChecked);
}
Jon B
  • 51,025
  • 31
  • 133
  • 161
1

You could remove then add the event handler. Assuming your code is in a method named ItemChecked

listView.ItemChecked -= ItemChecked;

// do whatever

listView.ItemChecked += ItemChecked;

However, I prefer checking for re-entrant calls.

object alreadyInItemChecked;

void ItemChecked(object s, EventArgs e)
{
   if (Monitor.TryEnter(alreadyInItemChecked))
   {
      try
      {
          // do whatever
      }
      finally
      {
          Monitor.Exit(alreadyInItemChecked)
      }
   }
 }
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
0

You can subscribe / unsubscribe to events as something like this.

        this.someObject.someObjectEvent += someEventHandler;
        this.someObject.someObjectEvent -= null;

So subscribe when you want the event to be fired and unsubscribe when not needed.

Jsinh
  • 2,539
  • 1
  • 19
  • 35