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.

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.

 

Author: 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.

Share This Post On
468 ad

Pin It on Pinterest

Share This
More in .NET, Application Development
java web start application
Building a Java Web Start Application

Close