Programmatically create new controls at runtime and add them to a form or inside a container in C#

Creating controls at runtime is fairly easy. When you click the example's Create Button button, the following code executes.

private int x1 = 12;
private int y1 = 41;

// Create a new button on the form.
private void btnCreateButton_Click(object sender, EventArgs e)
{
// Make a new button similar to the old one.
Button btn = new Button();
btn.Text = btnCreateButton.Text;
btn.Size = btnCreateButton.Size;
btn.Left = x1;
btn.Top = y1;
y1 += btn.Height + 6;

// Add this event handler to the button.
btn.Click += btnCreateButton_Click;

// Place the button on the form.
btn.Parent = this;
}

The code creates the new button by using the new keyword and then initializes its properties. This example adds the btnCreateButton_Click event handler to the new button's Click event. It finishes by setting the control's Parent property to the form. (This is the only non-obvious step.)

Creating a new control and placing it inside a container such as a GroupBox is also easy. When you click the program's Create Group Button button, the following code creates a new button inside a GroupBox.

private int x2 = 21;
private int y2 = 48;

// Create a new button inside the GroupBox.
private void btnCreateGroupButton_Click(object sender, EventArgs e)
{
// Make a new button similar to the old one.
Button btn = new Button();
btn.Text = btnCreateGroupButton.Text;
btn.Size = btnCreateGroupButton.Size;
btn.Left = x2;
btn.Top = y2;
y2 += btn.Height + 6;

// Add this event handler to the button.
btn.Click += btnCreateGroupButton_Click;

// Place the button inside the GroupBox.
btn.Parent = grpMoreButtons;
}

The code creates and initializes the button as before. The only difference is that this code sets the new button's Parent property to the GroupBox that should contain it.

Note that the button's X and Y location are relative to the container's upper left corner not the form's.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.