How to add and remove event on a button programmatically?

PreranaPrerana INMember ✭✭

Hello All,

I am using the following code to add and remove event on a button programmatically.

To add an event:

   EventHandler myEventhandler;
   myEventhandler = new EventHandler (HandleActivated);
   mybtn.Activated += myEventhandler;



To remove an event:

   mybtn.Activated -= myEventhandler;


HandleActivated as follows:

   void HandleActivated (object sender, EventArgs e)
    {
        Console.WriteLine("Event Handled --->>"+ DateTime.Now.ToString());
    }



Now the issue is, first time my event gets added and removed but when next time I want to add an event it doesnot work.I am using two buttons Add and Remove to add and remove events of a third button mybtn .


Why I cannot add an event to a button for the second time?? I have to handle the addition and removal of event programmatically.


Any help will be highly appreciated. Thanks in advance.

Best Answer

Answers

  • adamkempadamkemp USInsider, Developer Group Leader mod

    What is the type of mybtn? I've never seen the Activated event. The event usually used for buttons in iOS is TouchUpInside.

    Can you post an example project that shows the behavior you described?

  • AshokGelalAshokGelal USMember, Beta ✭✭

    I tried it too and doesn't seem to be working. So, it's not just you. I've never come across where I have to have other buttons controlling the Action of a third button. Probably a bug?

    @adamkemp‌ See attached project.

  • PreranaPrerana INMember ✭✭

    @adamkemp‌ type of mybtn is NSButton. About example project, exactly same project what @AshokGelal‌ has posted.


    @AshokGelal‌,yup its not working. Basically I do not want a third button controlling action of other buttons, I did that for testing purpose.


    All I want is adding and removing events to button at runtime. I have a functionality in my project where at a particular time I have to remove the event attached to a button and after some time add the event back to the same button. Is there any way to achieve it??

    Thanks for the answer.

  • PreranaPrerana INMember ✭✭

    @AshokGelal‌ ,yup I was thinking of doing the same and I guess it will pretty much satisfy the functionality,I will implement and confirm on this.

    So I guess there isn't any other way so far to add and remove event to a control programmatically at runtime??

  • AshokGelalAshokGelal USMember, Beta ✭✭

    It could well be a bug in Mono/Xam Mac. If I were you, I'd also try it on WinForms (in Windows using Visual Studio) and see. If it shows the same behavior, then I need to go and dust off my C# IN A NUTSHELL book and reread the chapter on Events and Delegates.

  • PreranaPrerana INMember ✭✭

    Yup I guess I need to do the same ..:)

    Thanks a ton for the answer!

Sign In or Register to comment.