Saturday, May 29, 2010

Add Controls During Runtime

When creating advanced applications, one will reach the point at which one is not satisfied with creating static forms only but wants to add controls dynamically during runtime.
Controls are basically just variables, e.g. of type Button, TextBox etc ... Like other variables they can also be initialized at runtime and then just have to be added to the form.
The following hopefully self-explaining code adds a new button to the form:
Button NewButton = new Button(); // initialize variable of type button
NewButton.Width = 100; // set width
NewButton.Height = 20; // set height
NewButton.Left = 10; // distance from left border
NewButton.Top = 50; // distance from top border
NewButton.Text = "Klick mich"; // label of the button
this.Controls.Add(NewButton); // add the new button to the form

In the last line of code the button variable is appended to the list this.Controls, which contains all controls of the form. It it is not added to this list, the control will also not be shown.

No comments:

Post a Comment