Aaron Azhari Aaron Azhari - 4 years ago 110
ASP.NET (C#) Question

Cannot create an object of type 'System.Collections.Generic.List'' from its string representation '(Collection)' for the '' property

I have created a custom web server control in asp.net. I am trying to render a List of a class in the RenderContents method.

Here is my code:

[ToolboxData("<{0}:News runat=server></{0}:News>")]
public class News : WebControl

public List<NewsItem> Items
List<NewsItem> items = (List<NewsItem>)(ViewState["Items"] == null ? new List<NewsItem>(): ViewState["Items"]);
return items;

ViewState["Items"] = value;

protected override void RenderContents(HtmlTextWriter output)
foreach (var item in Items)


First of all, when I drag drop this control onto a page, I can access the Items property from the property window in design-time.

Here's the aspx code of it:

<Aram:News ID="News1" runat="server" />

After I modify the Items (which appears with the value saying it is a Collection ) I don't see any updates on the design view.

And after I click ok, and starting the debug, I get the error:

Cannot create an object of type 'System.Collections.Generic.List`1[[AramWebControls.NewsItem, Custom Web Server Control, Version=, Culture=neutral, PublicKeyToken=null]]' from its string representation '(Collection)' for the 'Items' property.

Now that I look back at the aspx code of my control, it has its Items property set to '(Collection)'.

<Aram:News ID="News1" runat="server" Items="(Collection)" />

How to solve this? I'm gussing that my control should have the List controls as a content.

Any help will be appreciated.


Answer Source

I found the solution for this problem. First of all, the Items are of type List and that is a collection. It can not be persisted inside the News control tag. So it has to be a part of the content of News control tag. This calls for custom viewstate management.

For details you can first refer to Web Control Collection Property Example And then you need to override LoadViewState , SaveViewState and TrackViewState to handle the items. For more info on this one refer to Server Control Properties Example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download