Reflection implicit and explicit conversions.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am trying to dynamically create web controls from a database schema and
load them into the page. I am getting an error telling me "Cannot implicitly
convert type 'object' to 'System.Web.UI.Control'". How can i get arround
this so that my Control.Controls.Add(ctrl) will add successfully. Please see
code below:

private void Page_Load(object sender, System.EventArgs e)
{
System.Collections.Specialized.NameValueCollection nvc = new
System.Collections.Specialized.NameValueCollection();

nvc.Add("Text", "test 3");
nvc.Add("Enabled", "false");
nvc.Add("Columns", "50");
nvc.Add("rows", "50");
nvc.Add("TextMode", "MultiLine");

System.Web.UI.Control ctl =
CreateControl("System.Web.UI.WebControls.TextBox", nvc);

// adds the dynamic control to the placeholder control collection
plhControl.Controls.Add(ctl);

}

protected System.Web.UI.Control CreateControl(string controlTypeName,
NameValueCollection controlAttributes)
{
System.Web.UI.Control dynamicControl = null;

System.Type controlType = System.Type.GetType(controlTypeName);

if(controlType != null)
{
// create instance of type
object dynamicInstance =
controlType.Assembly.CreateInstance(controlType.FullName);

dynamicControl = Convert.ChangeType(dynamicInstance, controlType);
//dynamicControl = (typeof(dynamicInstance))dynamicInstance;

if(dynamicControl != null)
{
for(int i = 0; i < controlAttributes.Count; i++)
{
SetControlMemberValue(ref dynamicControl, controlAttributes.Keys,
controlAttributes);
}
}
}

return dynamicControl;
}


protected void SetControlMemberValue(ref System.Web.UI.Control instance,
string instanceMember, object instanceValue)
{
System.Type instanceType = instance.GetType();
object[] instanceValues = new object[1] { instanceValue };

System.Reflection.PropertyInfo currentProperty =
instanceType.GetProperty(instanceMember);

if(currentProperty != null)
{
if(currentProperty.PropertyType.IsEnum)
{
instanceValue = Enum.Parse(currentProperty.PropertyType,
instanceValue.ToString());
}
else
{
instanceValue = Convert.ChangeType(instanceValue,
currentProperty.PropertyType);
}


currentProperty.SetValue(instance, instanceValue, null);
}
}
 
you know, if for some reason you can't use the debugger, you could still use
the line information to know where the error happens!

but if I run my mind-embeded-virtual compiler/processor on your code.. I
guess that the bug happens on the line
dynamicControl = Convert.ChangeType(dynamicInstance, controlType);

guess what?
Convert.ChangeType() does return an object, doesn't it?

If you have found out the fix yet I would suggest something as complex as:
dynamicControl = (System.Web.UI.Control) Convert.ChangeType(dynamicInstance,
controlType);
 
Back
Top