Creating controls dynamically in C# WinForm

If you unsure of the number of records in your Database and would like to show them on a form in C#. You can easily create a Grid like structure dynamically to diaplay different controls at run-time and show data although data can also be shown in a DataGrid but for some reason you want to avoid using DataGrid.
Here is how it works, drop a panel on your form and name it panelHost. Example displays four labels in a single row and up-to ten total rows. Similarly other controls can be added to the panel

dynamic-controls

[code]
int y = 0, x;
int distance = 200;

for (int i = 0; i < 10; i++)
{
x = 0;
y += 30;

var lblSource = new Label();
lblSource.Location = new Point(x, y);
lblSource.Text = "text" + i;
panelHost.Controls.Add(lblSource);

x += distance;
var lblDestination = new Label();
lblDestination.Location = new Point(x, y);
lblDestination.Text = "text" + i;
panelHost.Controls.Add(lblDestination);

x += distance;
var lblField = new Label();
lblField.Location = new Point(x, y);
lblField.Text = "text" + i;
panelHost.Controls.Add(lblField);

x += distance;
var lblTransfer = new Label();
lblTransfer.Location = new Point(x, y);
lblTransfer.Text = "text" + i;
panelHost.Controls.Add(lblTransfer);
}
[/code]

Get Free Email Updates!

Signup now and receive free offers, discounts & coupon codes

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge