How do I pass variables to a buttons event method?

Wow, you guys are making this entirely to difficult. No need for any custom classes or method overrides. In this example I just need to pass a tab index number. You can specify whatever you want, so long as your method is expecting that value type.

button.Click += (sender, EventArgs) => { buttonNext_Click(sender, EventArgs, item.NextTabIndex); };

void buttonNext_Click(object sender, EventArgs e, int index)
    {
       //your code
    }

Cant you just set a property or member variable on the form that hosts the button and access these from the button click event?

EDIT: custom button class suggestion after feedback comment (not the same suggestion as above)

class MyButton : Button
{
    private Type m_TYpe;

    private object m_Object;

    public object Object
    {
        get { return m_Object; }
        set { m_Object = value; }
    }

    public Type TYpe
    {
        get { return m_TYpe; }
        set { m_TYpe = value; }
    }
}




Button1Click(object sender, EventArgs args)
{
  MyButton mb = (sender as MyButton);

  //then you can access Mb.Type
  //and  Mb.object
}

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);
}

Tags:

C#

Events