adding and removing components dynamically in c# .net

Add and Remove Controls Dynamically in Windows Forms Application in C#

Few weeks back, I described how to add and remove components dynamically from a JPanel in Java. I used the same approach for C# .NET. The logic is completely same however there are slight variations in the syntax. SO, here’s how you can add and remove controls dynamically in Windows Forms Application in C# .NET.

Working of the GUI

I have kept the GUI similar to the previous one. There are two combo boxes and one text box. There are contained in a TableLayoutPanel. For Java, I used GridLayout. TableLayoutPanel is equivalent to GridLayout. They are in tabular format. You get rows and columns. However, the difference is that you need to explicitly mention which control goes in which row and column. Because of this, using TableLayoutPanel is easier in some cases.

Like in the previous post, here I have also used arrays as dynamic variables. Turns out, that you can’t have dynamic variable names in .NET as well. What a shame ! Anyway, here we have two arrays of comboboxes and an array of textbox. If you’re fully aware of software requirements, this is the most easiest solution. You can limit the maximum number of rows that can be added by the user.

I’ve also added some validation like empty field detection and stuff like that.

Here’s a screenshot of the GUI.

Add and Remove Controls Dynamically in C# .NET

And here’s the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ApplicationDemo
{
    public partial class Form2 : Form
    {
        private ComboBox[] combo1;  // Array of comboboxes
        private ComboBox[] combo2;  // Array of comboboxes
        private TextBox[] text1;    // Array of textboxes
        private int count = -1;
        private int max_row = 10;
        private int empty_count = 0;
        private int rowIndex = 0;

        public Form2()
        {
            InitializeComponent();  // Visual Studio defined
            combo1_combo2_text1_array();    // declaring array for new row addition
        }

        private void combo1_combo2_text1_array()
        {
            combo1 = new ComboBox[max_row];
            combo2 = new ComboBox[max_row];
            text1 = new TextBox[max_row];
        }

        private void add_row_Click(object sender, EventArgs e)
        {
            if (count == max_row - 1)
            {
                MessageBox.Show("Maximum of 10 rows can be added");
                return;
            }
            else
            {
                count++;
                combo1[count] = new ComboBox();
                for (int i = 1; i <= 5; i++)                
                    combo1[count].Items.Add("Item " + i);                
                combo2[count] = new ComboBox();
                for (int i = 1; i <= 5; i++)                
                    combo2[count].Items.Add("Item " + i);                
                text1[count] = new TextBox();
                rowIndex = this.items_panel.RowCount++;               
                combo1[count].Dock = DockStyle.None;
                combo2[count].Dock = DockStyle.None;
                text1[count].Dock = DockStyle.None;
                combo1[count].Anchor = AnchorStyles.None;
                combo2[count].Anchor = AnchorStyles.None;
                text1[count].Anchor = AnchorStyles.None;                
                this.items_panel.Controls.Add(this.combo1[count], 0, rowIndex);
                this.items_panel.Controls.Add(this.combo2[count], 1, rowIndex);
                this.items_panel.Controls.Add(this.text1[count], 2, rowIndex);                
                this.items_panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50));       
               
            }
        }

        private void remove_row_Click(object sender, EventArgs e)
        {
            if (count > -1)  // Deleting one row at a time
            {
                this.items_panel.Controls.Remove(combo1[count]);
                this.items_panel.Controls.Remove(combo2[count]);
                this.items_panel.Controls.Remove(text1[count]);
                this.items_panel.RowCount--;  // decrementing the row count
                count--;
            }
        }

        private void reset_Click(object sender, EventArgs e)
        {
            textBox1.ResetText();
            comboBox1.ResetText();
            comboBox2.ResetText();
            for (int i = count; i > -1; i--)
            {
                this.items_panel.Controls.Remove(combo1[i]);
                this.items_panel.Controls.Remove(combo2[i]);
                this.items_panel.Controls.Remove(text1[i]);                                
            }
            this.items_panel.RowCount = 1;
            count = -1;
        }

        private void submit_Click(object sender, EventArgs e)
        {
            if (count > -1)
            {
                for (int i = 0; i <= count; i++)
                {
                    if (text1[count].Text == "" || combo1[count].SelectedItem == null || combo2[count].SelectedItem == null)
                        empty_count++;
                }
                if (empty_count > 0)
                {
                    MessageBox.Show("Empty Fields detected ! Please fill or select data for all fields");
                    empty_count = 0;
                }
                else
                    MessageBox.Show("No database connection for this application !!! ");
            }
            else if (count == -1)
                if (textBox1.Text == "" || comboBox1.SelectedItem == null || comboBox2.SelectedItem == null)
                    MessageBox.Show("Empty Fields detected ! Please fill or select data for all fields");
                else
                    MessageBox.Show("No database connection for this application");
        }

        private void cancel_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);   
        }
    }
}

Please note that “items_panel” is the TableLayoutPanel which contains the two comboboxes and the textbox. So, the most important operations are the ones including the “items_panel“.

That’s it for today. Stay tuned for a discount code for cheap Office for Mac 2016 and more Application Development tutorials.

 

Default image
Lahaul Seth
A programmer and a web developer, he is the founder of Lion Blogger. His main hobbies are web design & development and providing writing services to clients.