Have a look at Dynamic Data.
I recently found out about it and it's already saved me a lot of time.
Update:
Apologies - having reread the question, I don't think this is what you were after.
If you want to dynamically generate the form based on the records in your database, you may have to write your own engine.
A couple of suggestions though:
- I'd look at using reflection to load controls rather than large case statements. That way you could dynamically add different control types just by including the new assembly. You wouldn't have to write new code.
- Make sure you include a way to control the display order in your database. I note that you want to use a different table for each panel of controls. I'd advise against that because of the display order problem. If you have a table with a list of panels and a table with a list of data items + foreign key references to the panels, you'll be able to order them in a predictable and controllable way on the page.
Update: more info on reflection
Put simply, reflection is when you find out about details of an assembly at runtime. In this case, I suggest using reflection to load a control based on the information in your database.
So if you had a record in your database similar to the following:
FieldName DataType DisplayControl DisplayProperty
----------------------------------------------------------------------------------
FirstName System.String System.Web.UI.WebControls.TextBox Text
You could use some code like the following to generate the control on the page (note that it's untested):
// after getting the "PageItem" database records into a "pageItems" array
foreach (PageItem p in pageItems)
{
// get the type and properties
Type controlType = System.Type.GetType(p.DisplayControl)
PropertyInfo[] controlPropertiesArray = controlType.GetProperties();
// create the object
object control = Activator.CreateInstance(controlType);
// look for matching property
foreach (PropertyInfo controlProperty in controlPropertiesArray)
{
if (controlPropertiesArray.Name == p.DisplayProperty)
{
// set the Control's property
controlProperty.SetValue(control, "data for this item", null);
}
}
// then generate the control on the page using LoadControl (sorry, lacking time to look that up)
There is a really good page outlining how to do this here. It looks to be pretty much what you're after.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…