I need to generate form fields based on user selection or external data. What’s the most efficient way to add controls like TextBox, ComboBox, or Button dynamically during runtime? Also, how can I manage their layout and event handling?
Loading
I need to generate form fields based on user selection or external data. What’s the most efficient way to add controls like TextBox, ComboBox, or Button dynamically during runtime? Also, how can I manage their layout and event handling?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Deepika SawantRank #242 · 10.2K reputationPosted Oct 7, 2025, 5:09 AM EDT
Dynamically generating form controls like
TextBox,ComboBox, orButtonduring runtime is a common requirement in responsive UI scenarios—especially when the form structure depends on user input or external data. Here's a structured approach to doing this efficiently in .NET (WinForms or WPF):Dynamic Control Creation
You can create controls programmatically using their constructors and set properties as needed:
TextBox textBox = new TextBox(); textBox.Name = "txtName"; textBox.Text = "Enter name"; textBox.Location = new Point(10, 10); // For WinFormsFor WPF:
Layout Management
WinForms
Use layout containers like:
FlowLayoutPanel: Automatically arranges controls in flow.TableLayoutPanel: Grid-based layout.Panel: Manual positioning.Example with
FlowLayoutPanel:WPF
Use containers like:
StackPanel: Vertical or horizontal stacking.Grid: Flexible row/column layout.WrapPanel: Wraps controls based on available space.Example with
StackPanel:StackPanel stackPanel = new StackPanel(); this.Content = stackPanel; Button btn = new Button { Content = "Click Me" }; stackPanel.Children.Add(btn);Event Handling
Attach event handlers dynamically:
In WPF:
Managing Control State
To manage dynamically added controls:
Dictionaryto track them by name.Tagproperty to store metadata.Responding to External Data
If you're generating controls based on JSON or a database schema:
Example:
foreach (var field in fieldsFromJson) { if (field.Type == "text") { TextBox txt = new TextBox { Name = field.Name }; panel.Controls.Add(txt); } else if (field.Type == "dropdown") { ComboBox cmb = new ComboBox { Name = field.Name }; cmb.Items.AddRange(field.Options.ToArray()); panel.Controls.Add(cmb); } }Cynthia SathuragiriRank #937 · 2.2K reputationPosted Oct 8, 2025, 1:04 AM EDT
If your data includes field types, you can decide what control to create:
var formFields = new[] { new { Label = "Name", Type = "text" }, new { Label = "Gender", Type = "dropdown" }, new { Label = "Age", Type = "number" } };
Example: Create form fields from data
private void Form1_Load(object sender, EventArgs e)
{
// Example external data (could come from JSON, DB, API, etc.)
string[] fields = { "Name", "Email", "Age" };
int y = 20; // vertical position
foreach (string field in fields)
{
// Create a Label
Label lbl = new Label();
lbl.Text = field + ":";
lbl.Location = new Point(20, y);
lbl.AutoSize = true;
this.Controls.Add(lbl);
// Create a TextBox
TextBox txt = new TextBox();
txt.Name = "txt" + field;
txt.Location = new Point(100, y - 3);
this.Controls.Add(txt);
y += 30; // move down for next control
}
// Add a Submit button
Button btnSubmit = new Button();
btnSubmit.Text = "Submit";
btnSubmit.Location = new Point(20, y);
btnSubmit.Click += BtnSubmit_Click;
this.Controls.Add(btnSubmit);
}
private void BtnSubmit_Click(object sender, EventArgs e)
{
string name = ((TextBox)this.Controls["txtName"]).Text;
string email = ((TextBox)this.Controls["txtEmail"]).Text;
string age = ((TextBox)this.Controls["txtAge"]).Text;
MessageBox.Show($"Name: {name}\nEmail: {email}\nAge: {age}");
}
Sandhiya PriyaRank #26 · 43.2K reputationPosted Oct 14, 2025, 3:02 AM EDT
Absolutely! Dynamically adding controls in C# WinForms (or WPF, but I’ll focus on WinForms here) is a common scenario when the UI depends on user input or external data. Let me break it down step by step:
1. Creating Controls Dynamically
You can create controls like
TextBox,ComboBox, orButtonusing their constructors:// Example: Adding a TextBox dynamically TextBox txtDynamic = new TextBox(); txtDynamic.Name = "txtDynamic1"; txtDynamic.Text = "Enter text here"; txtDynamic.Location = new Point(20, 50); // x=20, y=50 txtDynamic.Size = new Size(200, 25); this.Controls.Add(txtDynamic); // Add to the formSimilarly, for a
Button:Button btnDynamic = new Button(); btnDynamic.Text = "Click Me"; btnDynamic.Location = new Point(20, 90); btnDynamic.Click += BtnDynamic_Click; // Add event handler this.Controls.Add(btnDynamic); // Event handler private void BtnDynamic_Click(object sender, EventArgs e) { MessageBox.Show("Dynamic button clicked!"); }2. Adding Multiple Controls in a Loop
If you need multiple fields based on user input or external data:
int startY = 20; for (int i = 0; i < 5; i++) { TextBox txt = new TextBox(); txt.Name = "txtDynamic" + i; txt.Location = new Point(20, startY); txt.Size = new Size(200, 25); // Optional: event handling txt.TextChanged += Txt_TextChanged; this.Controls.Add(txt); startY += 35; // Adjust vertical spacing } private void Txt_TextChanged(object sender, EventArgs e) { TextBox txt = sender as TextBox; Console.WriteLine($"{txt.Name} changed: {txt.Text}"); }3. Managing Layout Dynamically
Manually managing
Locationworks for simple forms. For more complex layouts, consider:FlowLayoutPanel – Automatically arranges controls horizontally or vertically:
FlowLayoutPanel panel = new FlowLayoutPanel(); panel.Location = new Point(10, 10); panel.Size = new Size(300, 300); panel.FlowDirection = FlowDirection.TopDown; panel.AutoScroll = true; this.Controls.Add(panel); for (int i = 0; i < 5; i++) { TextBox txt = new TextBox(); txt.Width = 200; panel.Controls.Add(txt); }TableLayoutPanel – Arrange controls in rows and columns for a grid-like layout.
4. Handling Events for Dynamic Controls
Dynamic controls can share the same event handler. Use
senderto know which control triggered it:private void Txt_TextChanged(object sender, EventArgs e) { TextBox txt = sender as TextBox; MessageBox.Show($"You typed in: {txt.Text}"); }5. Tips for Efficiency
Use Containers: FlowLayoutPanel or TableLayoutPanel reduces manual positioning.
Use Lists/Collections: Keep track of dynamically created controls in a
Listif you need to access them later.Event Reuse: Share event handlers between similar controls to avoid repetitive code.
Naming Conventions: Give dynamic controls meaningful names for easy identification.
Example: Full dynamic form with TextBoxes and Buttons
FlowLayoutPanel panel = new FlowLayoutPanel { Location = new Point(10, 10), Size = new Size(350, 300), FlowDirection = FlowDirection.TopDown, AutoScroll = true }; this.Controls.Add(panel); for (int i = 0; i { int index = (int)((Button)s).Tag; MessageBox.Show($"Button {index} clicked, Text: {panel.Controls[index * 2].Text}"); }; panel.Controls.Add(btn); }This approach is clean, keeps your code maintainable, and works for user-driven dynamic forms.