Add Controls Dynamically WinForms WindowsFroms C# VB.NET

1:55:00 am 0 Comments

Add controls dynamically In winforms Or windows froms Using C# And VB.NET

In this post i'm going to explain how to add controls dynamically in winforms and windows forms using C# and VB.NET.

Add Controls Dynamically in Winforms

For this i have used northwind database and Employees table to populate combobox and dataGridView.

First of all place two buttons on the form to add combobox and datagridview on button click and write below mentioned code in click event on each button respectively.







C# Code

01private void btnDropDown_Click(object sender, EventArgs e)
02        {
03            int x = 13, y = 70;
04            ComboBox cmbDynamic = new ComboBox();
05            cmbDynamic.Location = new System.Drawing.Point(x, y);
06            cmbDynamic.Name = "cmbDyn";
07            cmbDynamic.DisplayMember = "FirstName";
08            cmbDynamic.ValueMember = "EmployeeID";
09            cmbDynamic.DataSource = employeesBindingSource;
10            Controls.Add(cmbDynamic);
11 
12 
13        }

Here X and Y co-ordinates are used to define at which location the control needs to be placed.

01private void btnDataGrid_Click(object sender, EventArgs e)
02        {
03            int x = 13, y = 100;
04            DataGridView gvDynamic = new DataGridView();
05            gvDynamic.Location = new System.Drawing.Point(x, y);
06            gvDynamic.Name = "gvDyn";
07            gvDynamic.Width = 250;
08            gvDynamic.Height = 260;
09            gvDynamic.DataSource = employeesBindingSource;
10            Controls.Add(gvDynamic);
11        }

VB.NET Code

01Private Sub btnDropDown_Click(sender As Object, e As EventArgs)
02 Dim x As Integer = 13, y As Integer = 70
03 Dim cmbDynamic As New ComboBox()
04 cmbDynamic.Location = New System.Drawing.Point(x, y)
05 cmbDynamic.Name = "cmbDyn"
06 cmbDynamic.DisplayMember = "FirstName"
07 cmbDynamic.ValueMember = "EmployeeID"
08 cmbDynamic.DataSource = employeesBindingSource
09 Controls.Add(cmbDynamic)
10 
11 
12End Sub

01Private Sub btnDataGrid_Click(sender As Object, e As EventArgs)
02 Dim x As Integer = 13, y As Integer = 100
03 Dim gvDynamic As New DataGridView()
04 gvDynamic.Location = New System.Drawing.Point(x, y)
05 gvDynamic.Name = "gvDyn"
06 gvDynamic.Width = 250
07 gvDynamic.Height = 260
08 gvDynamic.DataSource = employeesBindingSource
09 Controls.Add(gvDynamic)
10End Sub


Build and run the code.

0 comments: