1

I want to execute something with a button click. But for that I need an additional parameter "string[] args".

private void button1_Click(object sender, EventArgs e, string[] args)

If I use this parameter, I get an error because I have to specify it somehow in the EventHandler which I do not know how to do?

this.button1.Click += new System.EventHandler(this.button1_Click);

Could someone explain to me how I would have to proceed here?

N3nntr0n
  • 23
  • 3
  • Why do you need the string[] args? The button event handler can't send anything for that parameter. – 230Daniel Jan 28 '21 at 11:34
  • Its a custom one I need for the code below. – N3nntr0n Jan 28 '21 at 11:37
  • (sender, EventArgs) => { buttonNext_Click(sender, EventArgs, item.NextTabIndex); }; I used that for now. It also works – N3nntr0n Jan 28 '21 at 11:38
  • I would be a bit careful using lambdas as event handlers. One problem is that it is quite difficult to unregister them. In some cases that does not matter, but you need to know when it does to write correct code. – JonasH Jan 28 '21 at 12:19

1 Answers1

-1

use this code in form.designer.cs

private void InitializeComponent()
{
  string[] args = new string[] { "param1", "param2" };
  MyButton myButton = new MyButton(args);
  this.SuspendLayout();
  // 
  //myButton
  // 
  myButton.Location = new System.Drawing.Point(230, 121);
  myButton.Name = "myButton";
  myButton.Size = new System.Drawing.Size(175, 31);
  myButton.TabIndex = 0;
  myButton.Text = "Test Click";
  myButton.UseVisualStyleBackColor = true;
  myButton.ButtonClick += MyButton_ButtonClick;


  // 
  // Form1
  // 
  this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  this.ClientSize = new System.Drawing.Size(800, 450);
  this.Controls.Add(myButton);
  this.Name = "Form1";
  this.Text = "Form1";
  this.ResumeLayout(false);
}
private void MyButton_ButtonClick(object Sender, System.EventArgs e, string[] args)
{
   //do works.......
   MyButton btn = Sender as MyButton;
   MessageBox.Show(args[0] + " -- " + args[1] + " -- " + btn.Name);       
}

and add this class

public class MyButton : Button
{
   public event ClickEventHandler ButtonClick;
   public delegate void ClickEventHandler(object Sender, EventArgs e, string[] args);
   private string[] _args;
   public MyButton(string[] args)
   {
      _args = args;
   } 

   protected override void OnClick(EventArgs e)
   {
      if (ButtonClick != null)
      {
          ButtonClick(this, e, _args);
      }
   }
}

This code works perfectly.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17