Fun with setting subproperties through reflection
-
What I'm trying to do is set up a system that can read records from a database and build a form according to the information contained in those records. I've largely succeeded, but I'm having difficulty setting up a way to set sub-properties. For demonstration purposes, I will use a concrete example. Let's say I'm trying to set up a label. I want to use database records to set the label's properties. One of the properties I want to set is Font. In the case of Font, there are subproperties, i.e. Bold, Italic, Name, Size, etc. In my example, I want the font to be bold, which means I need to set the Font.Bold subproperty to True. I've pulled the applicable data from the database into a dataset called dsMyDataSet, set up as follows: tblTemplateControls ControlID | ControlType 1 | System.Web.UI.WebControls.Label tblControlProperties PropertyID | ControlID | PropertyName | PropertyValue | ParentPropertyID 1 | 1 | Font | NULL | 0 2 | 1 | Bold | True | 1 3 | 1 | Text | Hi, Mom! | 0 Here's the code I'm using:
//Instantiate controls. This is well-developed and works great. I include it for context. for (int n = 0; n < this.dsMyDataSet.Tables["tblTemplateControls"].Rows.Count; n++) { dr = this.MyDataSet.Tables["tblTemplateControls"].Rows[n]; Type myControlType = typeof(Control).Assembly.GetType((string)dr["ControlType"]); ConstructorInfo myControlContructor = myControlType.GetConstructor(System.Type.EmptyTypes); Control myControl = (Control)myControlContructor.Invoke(null); myControl.ID = Convert.ToString((int)dr["ControlID"]); //Set the properties of the control. The works well for top-level properties like Text. DataRow[] Properties = this.dsMyDataSet.Tables["tblControlProperties"].Select("ControlID = " + myControl.ID); for (int j = 0; j < Properties.Length; j++) { DataRow Property = Properties[j]; if ((int)Property["ParentPropertyID"] == 0) //This property does not have a parent property. { foreach (PropertyInfo pi in myControlType.GetProperties()) { if (pi.Name == Property["PropertyName"].ToString().Trim())