Create controls dynamically from database
In my cms’ I usually have the option of creating controls from the database. This is just a simple use for reflection but allows me to add controls to page just by adding a new row. If its one of my controls it supports a persistance system that allows the control to save and restore itself easily.
public static class ControlFactory { /// <summary> /// /// </summary> /// <param name="creationString">In the format of 'Namespace.ControlName,AssemblyName'</param> /// <returns>The control if it can be found and created from the assembly</returns> public static Control CreateControl(string creationString) { Control ctrl = new Control(); try { Type ctrlType = Type.GetType(creationString,true); //if we got here we found it ctrl = Activator.CreateInstance(ctrlType) as Control; } catch (Exception Ex) { ctrl = null; //throw; } return ctrl; } public static Control CreateControl(string creationString, string persistanceData) { Control ctrl = CreateControl(creationString); /* ========== "if it implements IPersist the try and restore its data" ========== */ if (ctrl!= null && ctrl is IPersist) { (ctrl as IPersist).Restore(persistanceData); } return ctrl; } } /// <summary> /// Used by controls to store their state to text and back again /// </summary> /// <remarks>Not using .ToString and parse as we don;t want to override that functionality</remarks> public interface IPersist { bool Restore(string persistanceData); string Perist(); }