[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Create controls at runtime and add them to a form or inside a container in C#

This example shows how to create controls at runtime and place them either directly on the form or inside a container. When you click the example's Create Button button, the following code creates a new button on the form.

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 (the same event handler it is currently executing) to the new button's Click event. It finishes by setting the control's Parent property to the form. (That's is the only non-obvious step.)

Creating a new control and placing it inside a container such as a GroupBox is just as easy. When you click Create Group 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 Left and Top properties are relative to the container's upper left corner not the form's.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.