Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

C# Button Click with additional Parameter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...