How do I pass variables to a buttons event method?

前端 未结 8 1778
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 08:29

I need to be able to pass along two objects to the method being fired when I click a button. How do I do this?

So far I\'ve been looking at creating a changed E

相关标签:
8条回答
  • 2020-12-14 09:23

    Would need to see more code to give a better answer, but you could create an event that takes your CompArgs as a parameter and is fired when the buttonEvent is captured

    0 讨论(0)
  • 2020-12-14 09:30

    I'd create a new Button and override the OnClick method. Rather than passing down the EventArgs, pass a new derived class in with your additional members.

    On the delegate receiving the event, cast the given EventArgs to the more derived class you're expecting to get, alternatively setup a new Event that will be triggered at the same time when the button is pressed and hook up to that instead to make things more implicit.

    Example Code:

     public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            ButtonEx b1 = new ButtonEx();
            b1.OnCustomClickEvent += new ButtonEx.OnCustomClickEventHandler(b1_OnCustomClickEvent);
        }
    
        void  b1_OnCustomClickEvent(object sender, ButtonEx.CustomEventArgs eventArgs)
        {
            string p1 = eventArgs.CustomProperty1;
            string p2 = eventArgs.CustomProperty2;
        }
    }
    
    public class ButtonEx : Button
    {
        public class CustomEventArgs : EventArgs
        {
            public String CustomProperty1;
            public String CustomProperty2;
        }
    
        protected override void  OnClick(EventArgs e)
        {
            base.OnClick(e);
            if(OnCustomClickEvent != null)
            {
                OnCustomClickEvent(this, new CustomEventArgs());
            }
        }
    
        public event OnCustomClickEventHandler OnCustomClickEvent;
        public delegate void OnCustomClickEventHandler(object sender , CustomEventArgs eventArgs);
    }
    
    0 讨论(0)
提交回复
热议问题