-1

I'm in WinForms C#. I'm in a loop delegating the click to a function.

foreach (Class.Item item in _searchName)
        {
            indexGroup++;
            if (indexGroup <= MAX_SEARCHES)
            {
                myCntrl = (GSSearcher)panelSearch.Controls["gsSearcher" + indexGroup.ToString()];

                myCntrl.Visible = true;
                myCntrl.SetId = item.Id;
                myCntrl.SetText1 = item.Name;
                myCntrl.SetText2 = item.Description;
                string[] onlyDate = item.DateCreate.ToString().Split(' ');
                myCntrl.SetText3 = onlyDate[0].ToString();

                //HAY QUE MIRAR ESTO.
                myCntrl.MyClick += delegate { ClickIdToLoad(item.Id); };
            }
        }

This is inside a searcher and everytime someone search the loop is assigning the function again. So when I put a breakpoint to the function ClickIdToLoad, this stops there a lot of times. I need to "undelegate" the function or something like this once is already delegated.

Josep
  • 1
  • 9
  • Well, with every iteration you are subscribing a new anonymous delegate to the event. You could either rework your code to keep a reference (and remove as shown here http://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c-sharp ) or try to move the `+=` outside your loop. – ChrisK Sep 29 '16 at 11:57
  • Would it be possible to save the `ìtem.id` in the [Tag](https://msdn.microsoft.com/de-de/library/system.windows.forms.control.tag(v=vs.110).aspx) of your control? It seems that this is a custom control, so you could query the `Tag` in the event handler and just call `ClickIdToLoad((int)item.Id)`. This way you wouldnt need to keep a bunch of references around. – ChrisK Sep 29 '16 at 12:03
  • Just don't assign the MyClick event handler inside the loop at all. There is no point to that. Assign it in the form class constructor, all of these GSSearcher controls just need a single event handler. In that event handler, cast the *sender* argument to GSSearcher and use the SetId property. Or override the OnClick() method inside the GSSearcher class. – Hans Passant Sep 29 '16 at 12:32
  • ChrisK i made the tag solution and it's working. Nice idea!!! grateful!! how i can vote +1 on u ? – Josep Sep 29 '16 at 13:14

1 Answers1

0

Thanks to Chrisk I used this solution:

Would it be possible to save the ìtem.id in the Tag of your control? It seems that this is a custom control, so you could query the Tag in the event handler and just call ClickIdToLoad((int)item.Id). This way you wouldnt need to keep a bunch of references around. – ChrisK 1 hour ago

But i'm not "undelegating".

Thanks ChrisK!!

Josep
  • 1
  • 9