How to create Dynamic Controls in C# ?

How to create Control Arrays in C# ?

Visual Studio .NET does not have control arrays like Visual Basic 6.0 does. The good news is that you can still set things up to do similar things. The advantages of C# dynamic controls is that they can be created in response to how the user interacts with the application. Common controls that are added during run-time are the Button and TextBox controls. But of course, nearly every C# control can be created dynamically.

C# dynamic-controls creation

How to create Dynamic Controls in C# ?

The following program shows how to create a dynamic TextBox control in C# and setting the properties dynamically for each TextBox control. Drag a Button control in the form and copy and paste the following source code . Here each Button click the program create a new TextBox control dyanmically.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { int cLeft = 1; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { AddNewTextBox(); } public System.Windows.Forms.TextBox AddNewTextBox() { System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox(); this.Controls.Add(txt); txt.Top = cLeft * 25; txt.Left = 100; txt.Text = "TextBox " + this.cLeft.ToString(); cLeft = cLeft + 1; return txt; } } }