Add button & its click event programmatically in C#

We are going to create an application in which we'll add button in its click event programmatically. You just have to create a new object of "Button" format it (location, name, text, size etc), assign a click event, add it to the form and declare and initialize that click event.
  • Open visual studio and create new "Windows Form Application" project.
  • Double click at form and you will be in that form's "Form1_Load" event code.
  • Now add following code in you 
private void Form1_Load(object sender, EventArgs e)
{
      Button MyBtn = new Button();

      // Button formation and other setting
      MyBtn.Location = new System.Drawing.Point(100, 100);
      MyBtn.Name = "MyButton";
      MyBtn.Size = new System.Drawing.Size(75, 23);
      MyBtn.TabIndex = 0;
      MyBtn.Text = "My Button";
      MyBtn.UseVisualStyleBackColor = true;

      // Set button click event
      MyBtn.Click += new EventHandler(Button_Click);

      // Add button control in form
      this.Controls.Add(MyBtn);
}
In above code we have added a click event "Button_Click". Now we have to define it too. Add following code.

private void Button_Click(object sender, EventArgs e)
{
      MessageBox.Show("It is working :)");
}

Now run your application (press F5) and see the result.



Comments

Popular posts from this blog

Add images in ListView (C#)

Resize and Save Multiple Images in C#