I want to pass an int list (List) as a declarative property to a web user control like this:
I believe the problem is the set{}. The type converter want to change the List<int>
back into a string, but CanConvertFrom()
fails for List<int>
.
You can pass it into a string and split on comma to populate a private variable. Does not have the nicety of attribution, but will work.
private List<int> modules;
public string ModuleIds
{
set{
if (!string.IsNullOrEmpty(value))
{
if (modules == null) modules = new List<int>();
var ids = value.Split(new []{','});
if (ids.Length>0)
foreach (var id in ids)
modules.Add((int.Parse(id)));
}
}
WHile I can't say I have any particular experience with this error, other sources indicate that you need to add a conversion to the type InstanceDescriptor. check out:
http://weblogs.asp.net/bleroy/archive/2005/04/28/405013.aspx
Which provides an explanation of the reasons or alternatively:
http://forums.asp.net/p/1191839/2052438.aspx#2052438
Which provides example code similar to yours.
pass the list from the code behind...
aspx:
<UC:MyControl id="uc" runat="server" />
code-behind:
List<int> list = new List<int>();
list.add(1);
list.add(2);
list.add(3);
uc.ModuleIds = list;
The way I normally do this is to make the property wrap the ViewState collection. Your way looks better if it can be made to work, but this will get the job done:
public IList<int> ModuleIds
{
get
{
string moduleIds = Convert.ToString(ViewState["ModuleIds"])
IList<int> list = new Collection<int>();
foreach(string moduleId in moduleIds.split(","))
{
list.Add(Convert.ToInt32(moduleId));
}
return list;
}
}
I think that you're best option is to make your usercontrol have a DataSource-style property.
You take the property as an object and then do some type checking against IList/ IEnumerable/ etc to make sure that it is correct.