Creating forms and form controls using the IDE is pretty straightforward. When the form is rather static, you can lay it all out in advance. However when the layout of the form is based on information gathered at run time, you have to be able to create and place controls on your form dynamically.
This is not so hard, but what seems to be complicated (and actually turns out to be pretty straightforward), is assigning event handlers to dynamically created controls. Here's how.
This is a problem that came up in a couple of the example projects on this site that was used to illustrate recursion - the Sudoku Solver and generator. and Roadmap Generation. You can read about the solution to the roadmap problem here
This turned out to be harder than planned, because the original idea was to use some form of grid control, such as flexgrid, or even to embed a spreadsheet control on a form, but both these ideas hit problems because of changes between Excel 2003 and 2007 where some controls were no longer supported and a viable alternative was not included in the updated version.
So in the end, I decided to go for dynamically created textboxes. This caused 2 major challenges
- Having to create event handlers dynamically for each textbox
- Figuring out how to prettify a sudoku grid using the limited textbox options for border controls
In this section we'll look at the solution to these 2 problems.