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.
Now run your application (press F5) and see the result.
- 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.{
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);
}
private void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("It is working :)");
}
{
MessageBox.Show("It is working :)");
}
Now run your application (press F5) and see the result.
Comments
Post a Comment
Welcome to fc-3