How to create controls dynamically and add event to them in winform


In this article we learn how to create controls dynamically and add it to winform. We also set various properties for dynamic controls like text, size, location. We create events and attach to the newly created winform controls..

The status of this resource is Pending and require some modification by the author.

Create new window application. And design winform as below with one button control.
1

Create button click event. In click event create new button and set properties like text, location. Then add this newly created button to form. Add event handler for click event for dynamic button.

Run application and click on Create New Button. Then new button with click event added on form.

2

To check click event of click on dynamic button. You will get output like below.

3

Source Code:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace DynamicControls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//Dynamic button created here
Button btn = new Button ();
this.Controls.Add(btn);
btn.Location = new Point(25, 50);
btn.Size = new Size(233,27);
btn.Text = "Dynamic Button";
//Click event for dynamic button attahced
btn.Click += new EventHandler (btn_Click);
}

private void btn_Click(object sender, EventArgs e)
{
MessageBox.Show("Dynamic button clicked.");
}

}
}


Related Articles

More articles: Dynamically add controls WinForms Controls

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: