tags:

views:

4556

answers:

6

Using C# 2.0 what is the best way to implement dynamic form controls?

I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way?

+1  A: 

What do you mean by “dynamic”? A new, fixed set of controls for each data row in the data set? Then use a UserControl that contains your controls.

Or do you mean that, depending on your data layout, you want to provide the user with a customized set of controls, say, one TextBox for each column?

Konrad Rudolph
+1  A: 

Yeah, I've found manually layout out controls (incrementing their Top property by the height of the control plus a margin as I go) to be reasonably effective.

Another approach is to place your controls in Panels with Dock set to Top, so that each successive panel docks up against the one above. Then you can toggle the visibility of individual panels and the controls underneath will snap up to fill the available space. Be aware that this can be a bit unpredictable: showing a hidden panel that's docked can sometimes change its position relative to other docked controls.

Matt Hamilton
+6  A: 

You can use panels with automatic layout such as FlowLayoutPanel and TableLayoutPanel.

Unfortunately there are only 2 panels with automatic layout out of box but you can create custom layout panel.

I would recommend you to read following articles:

How to: Create a Resizable Windows Form for Data Entry

Walkthrough: Creating a Resizable Windows Form for Data Entry

Another option would be using of WPF (Windows Presentation Presentation).
WPF is a perfect match for your task.
WPF controls can be hosted in WinForms apps so you don't have to switch to it completely.

aku
+1  A: 

Well that's the way we are doing it right now on a project. but that's only useful for simple cases. I suggest you use some sort of template for more complex cases.

For instance I used Reflection to map a certain type of control to a certain property on my domain objects on an older project.

You could try generating the code from templates using t4 see T4 Templates in Visual Studio for Code Generation Screencast for a simple example. You can apply this to WinForms.

Also DevExperience has a nice ( expensive ) framework, see DevExpress eXpressApp Framework™ .

Mihai Lazar
A: 

the data is dynamic in the sense that the controls displayed differ depending on the data, ie a textbox or 2 for one and a set of radio buttons for another.

So i think ill just do it manually, since im not use i want to go through the hassle of using or creating a LayoutPanel.

Thanks all!

Sam
+2  A: 

@Sam I know this question was about Windows Forms, but you should definitely start looking at WPF. This sort of scenario is really easy in WPF with DataTemplates and TemplateSelectors.

Matt Hamilton