Search code examples
c#asp.netcustom-server-controlsdatabound-controls

Generic - Typed CompositeDataBound Control


I have a compositeDatabound control: MyGrid with MyItemTemplate with container of MyContainer. I have a class User.

public class MyGrid: CompositeDataBoundControl
{
  [TemplateContainer(typeof(MyGrid.MyContainer))]
  public ITemplate MyItemTemplate
  {
     //get;set;
  }
  public class MyContainer: Control, INamingContainer
  {
    //return DataItem of type User
  }
  //rest of all code
}

This helps me to use: <%# Container.DataItem.FirstName %> where FirstName is a property in User Class.

Now I want to make it a Generic Grid i.e. MyGrid<T>

So I have to modify my TemplateContainer as well like this:

[TemplateContainer(typeof(MyGrid<>.MyContainer))]

The MyGrid class compiles fine without any errors: I create a concrete class i.e.

MyUserGrid: MyGrid<User> and it compiles fine as well. But that is not liked by ASP.NET. I mean the class itself compiles without error but I can no longer use:

<%# Container.DataItem.User.FirstName %>

Any help / ideas how to make this Typed Grid to Generic Typed Grid?

This is something I found and looks kind of complex. Is that the right and the only way? I don't want to pass a type in the property as in the link. Instead I will be creating my concrete class by deriving from a generic class.

My try keeps giving me this error: Invalid expression term '>'

To add: It's ASP.NET 2.0 WebForms


Solution

  • I changed the class MyGrid to an abstract MyGrid class and made the ITemplate property abstract as well. Then in my concrete derived class MyUserGrid:MyGrid I implemented the ITemplate property with TemplateContainer attribute like:

    [TemplateContainer(typeof(MyUserGrid.MyContainer))]
    

    It isn't that neat but still good enough generic for my usage. But feel free if to comment if you have a better solution.