Add Controls Dynamically WinForms WindowsFroms C# VB.NET

In this post i'm explaining how to Add Controls Dynamically In Winforms Windows Forms Application Using C# And VB.NET

I have used northwind database and Employees table to populate combobox and dataGridView.

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

Add Controls Dynamically in Winforms Windows Forms


C#
private void btnDropDown_Click(object sender, EventArgs e)
        {
            int x = 13, y = 70;
            ComboBox cmbDynamic = new ComboBox();
            cmbDynamic.Location = new System.Drawing.Point(x, y);
            cmbDynamic.Name = "cmbDyn";
            cmbDynamic.DisplayMember = "FirstName";
            cmbDynamic.ValueMember = "EmployeeID";
            cmbDynamic.DataSource = employeesBindingSource;
            Controls.Add(cmbDynamic);
            
            
        }

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

private void btnDataGrid_Click(object sender, EventArgs e)
        {
            int x = 13, y = 100;
            DataGridView gvDynamic = new DataGridView();
            gvDynamic.Location = new System.Drawing.Point(x, y);
            gvDynamic.Name = "gvDyn";
            gvDynamic.Width = 250;
            gvDynamic.Height = 260;
            gvDynamic.DataSource = employeesBindingSource;
            Controls.Add(gvDynamic);
        }

VB.NET
Private Sub btnDropDown_Click(sender As Object, e As EventArgs)
 Dim x As Integer = 13, y As Integer = 70
 Dim cmbDynamic As New ComboBox()
 cmbDynamic.Location = New System.Drawing.Point(x, y)
 cmbDynamic.Name = "cmbDyn"
 cmbDynamic.DisplayMember = "FirstName"
 cmbDynamic.ValueMember = "EmployeeID"
 cmbDynamic.DataSource = employeesBindingSource
 Controls.Add(cmbDynamic)


End Sub

Private Sub btnDataGrid_Click(sender As Object, e As EventArgs)
 Dim x As Integer = 13, y As Integer = 100
 Dim gvDynamic As New DataGridView()
 gvDynamic.Location = New System.Drawing.Point(x, y)
 gvDynamic.Name = "gvDyn"
 gvDynamic.Width = 250
 gvDynamic.Height = 260
 gvDynamic.DataSource = employeesBindingSource
 Controls.Add(gvDynamic)
End Sub


Build and run the code.

If you like this post than join us or share

0 comments:

Find More Articles