Dynamically generated buttons

Aloha!
Currently, I am working on another small app which I will present here shortly. Its function will be disclosed later as that fact is of no importance to this post. What is important is that some buttons the app will create automatically depending on some user settings. The buttons will be arranged in, let’s call it excel-style, in a table with equal size cells. So, the buttons need to be generated in a loop. That seems to be an easy task, but it becomes a bit trickier if you want them to perform different action. Here’s how to do that.

The code above shows how to generate the buttons with individual action performed by each button. But the solution above requires you to know how many buttons your program will create and still manually write separate switch/case instructions for each but. Tricky, but in some cases might be enough.

If it isn’t enough C# gives you opportunity to create actions delegates and store them in a dictionary.

These are two approaches to dynamically created buttons with individual actions for each button.

This post has been compiled from:
http://stackoverflow.com/questions/1434282/how-do-i-create-5-buttons-and-assign-individual-click-events-dynamically
http://stackoverflow.com/questions/33107026/dynamic-switch-cases
http://stackoverflow.com/questions/8414930/is-it-possible-to-declare-generic-delegate-with-no-parameters