asp.net.netcustom-server-controls

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:

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

  [Bindable(true)] 
  [Category("Appearance")] 
  [DefaultValue("")] 
  [Localizable(true)] 
  public List<NewsItem> Items 
  { 
   get 
   { 
    List<NewsItem> items = (List<NewsItem>)(ViewState["Items"] == null ? new List<NewsItem>(): ViewState["Items"]); 
    return items; 
   } 

   set 
   { 
    ViewState["Items"] = value; 
   } 
  } 

  protected override void RenderContents(HtmlTextWriter output) 
  { 
    foreach (var item in Items) 
     item.RenderControl(output); 

  } 
 } 

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=1.0.0.0, 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.

Thanks.


Solution

  • 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