Me and the webforms parser are having some difficulties today, regarding control properties I hope some of you can help me with!
I have a Control with a property named Value with object as type. When every time I declare it in my aspx I get the error
Cannot create an object of type 'System.Object' from its string representation '...' for the 'Value' property.
Wtf, isnt everything Objects? :)
I then tried to add a TypeConverter on my property, but no luck.
My Control
[ParseChildren(true, "Value")]
[TypeConverter(typeof(ExpandableObjectConverter))]
[ControlBuilder(typeof(ParamControlBuilder))]
public class Param : Control
{
public string Name { get; set; }
[TypeConverter(typeof(StringToObjectConverter))]
public object Value { get; set; }
protected override void AddParsedSubObject(object obj)
{
base.AddParsedSubObject(obj);
}
public override void DataBind()
{
base.DataBind();
}
protected override void DataBindChildren()
{
base.DataBindChildren();
}
}
The TypeConverter
public class StringToObjectConverter : TypeConverter
{
public override bool IsValid(ITypeDescriptorContext context, object value)
{
return true;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(object))
{
return true;
}
if (destinationType == typeof(InstanceDescriptor))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value.ToString();
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(object))
{
return (object)value;
}
if (destinationType == typeof(InstanceDescriptor))
{
return new InstanceDescriptor(typeof(object).GetConstructor(new Type[] { }), new object[] { });
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
What i want to do is to be able to write in my aspx page the following
<my:param name="A object" value="<# value_of_a_method()" %> runat="server" />
<my:param name="A object" value="this_is_just_a_string" runat="server" />
The first example works fine, the second fails with mentioned error. And no, i can't believe that the only way around this is to databind everytime, even for constant strings like
<my:param name="A object" value='<%# "this_is_just_a_string" %>' runat="server" />