Is there a better way to create Form Controls for properties of a class? Right now, I iterate through all properties of a class and have a method to create the Form Control for that property based on the type of the property.
private void AddControl(PropertyInfo p, string name = null, Color? c = null, int count = 0)
{
Label newLabel = new Label();
TableLayoutPanel tp = new TableLayoutPanel();
Control ctrl = new Control();
tp.ColumnCount = 2;
tp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200F));
tp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 215F));
tp.Margin = new Padding(0);
tp.Name = "tp";
tp.RowCount = 1;
tp.RowStyles.Add(new RowStyle(SizeType.Absolute, 28F));
tp.Size = new System.Drawing.Size(380, 28);
tp.Location = new Point(0, 14 + num * 28);
newLabel.Name = "lbl_" + num;
newLabel.Text = GetPropertyAttributes(p); // gets a custom attributes for the property
newLabel.AutoSize = true;
newLabel.Anchor = AnchorStyles.Left;
tp.Controls.Add(newLabel);
ToolTip myToolTip = new ToolTip();
switch (p.PropertyType.Name)
{
case "String":
ctrl = new TextBox();
ctrl.Tag = "String";
ctrl.Size = new System.Drawing.Size(170, 20);
goto case "common";
case "Boolean":
ctrl = new CheckBox();
goto case "common";
case "Array[]":
Console.WriteLine("Array");
break;
case "Int32":
ctrl = new TextBox();
ctrl.Tag = "Int";
ctrl.Size = new System.Drawing.Size(40, 20);
goto case "common";
case "Double":
ctrl = new TextBox();
ctrl.Tag = "Double";
ctrl.Size = new System.Drawing.Size(40, 20);
goto case "common";
case "IList`1":
if (ClassExists(p.Name)) // ClassExists checks if the property is a class itself
{
ctrl = new Button();
ctrl.Text = "Add";
ctrl.Tag = p;
ctrl.AutoSize = true;
ctrl.Click += new EventHandler(AddButton_Click);
}
else
{
// TODO create gridview
}
goto case "common";
case "common":
ctrl.Anchor = AnchorStyles.Left;
ctrl.Name = name ?? GetPropertyAttributes(p);
ctrl.Font = new Font("Consolas", 9);
ctrl.KeyPress += new KeyPressEventHandler(textBoxKeyPress);
if (c != null)
{
tp.BackColor = c ?? Color.Black;
}
tp.Controls.Add(ctrl);
formControls.Add(tp); // List<Control>
break;
default:
ctrl = new Button();
ctrl.Text = "Add";
ctrl.Tag = p;
ctrl.AutoSize = true;
ctrl.Click += new EventHandler(AddButton_Click);
goto case "common";
}
}
private void AddControls()
{
foreach (Control ctrl in formControls)
{
MainPanel.Controls.Add(ctrl); // MainPanel is a Panel Control
}
}
Can it be simplified? I may have to add more types to it.