Dynamic Controls and Static Events with Different output

The title sounds little awkward.. Well. This code explains an easy and a good coding practice in handling dynamic controls and writing events for them.

Let me explain the scenario, one of my friend needs a code for a garment fault detection system; the machine checks the cloths and detects the faults. Each fault has to appear as button and when the user clicks the button it has to do some other thing corresponding to that fault.

The problem is, we are not aware of the number of faults each piece of cloth has. So we have to generated the controls dynamically and the events.

Only one thing we know that, the hardware is capable of detecting 10 different types of faults. So maximum we can get 10 and that’s it.

He was so confused whether to write 10 different event handlers and assign them, to dynamic controls by writing some conditional branching statements.

The code below is simple but powerful, it makes life easier with just 2 methods. Let’s get into the action.

Some how you can get a parameter which says how many controls you have to generate dynamically. I store them in a List (for demonstration)

image

Another method to create the controls and load them to the Windows Form.  (here I’m using a Windows Form application)

image

As you see here I’m not keeping the references of the Button controls, but I’m assigning a single event to all of them.

This event is the only thing I have to refer the controls. But let’s see how I use the single event to distinguish the different buttons and ask them to do different tasks.

As I mentioned earlier it so simple…

I’m loading the strings to the List from a method (which I haven’t metioned here, because getting the parameter which decides the number of dynamic controls depends on the scenario you are working on).

image

This is cool, I identify the Buttons with their Text field, you can use any of the fields which is comfortable and suits your need.

The power of this method is; it’s very simple, I’m not keeping any references to the Buttons. The same piece of code can be used to generate the any number of controls without any modifications.

And you have to write only one event handler for all the controls like the above method.

Just imagine 10 controls and 10 references and 10 different even handlers, and dynamically comparing them and calling every time. 😦 It’s too much of a work. But this is really cool.

You can design your actions in a separate library (.dll) and call them in the case : of the switch statements, that gives a good design also. So whenever you want the actions to be modified, you just have to change a seperated .dll file rather changing the main assembly.

Advertisement