What is the correct way to use generic types in UserControl?

For starters, maybe someone can help with the title of the question a little better.

What am I trying to accomplish:

Below is a very simple example of what I am trying to achieve using only the main working parts in order to be able to find the solution I'm looking for.

I want to be able to create the following file in .ascx.cs codebehind:

public partial class DynamicControl<T> : System.Web.UI.UserControl where T : class
{
    public List<T> Items;

    public void Add(T item) {
        Items.Add(item);
    }
}

Correctly refer to this in the .ascx file:

<% foreach (var item in Items) { %>
    <p>item.Name</p>
<% } %>

And load this into an .aspx file with this tag:

<custom:DynamicControl ID="DynamicControl1" ItemType="Person" runat="server" />

Or even in .aspx.cs codebehind as:

DynamicControl1.ItemType = Type.GetType("Person");

Indeed, whatever is possible.

I just need a way to create common user controls on my website, where I can set the item type programmatically (or in a tag) and work with it both with .ascx.cs and .ascx files, and with an .aspx link.

What I tried:

1) DynamicControlBuilder ControlBuilder, [ControlBuilder(typeof(DynamicControlBuilder))]. , .aspx.designer.cs, .ascx , .

2) DynamicControl, , , - DynamicControl<dynamic> - , , , , .

3) , - Add<T>(T item) where T : class, , , ... , , , . List<T> Items, , , .

!

+4
1

, ?

, , IDisplayable, , . , , .

, DisplayItemsControl: System.Web.UI.UserControl {    ;

public void Add(IDisplayable item) {
    Items.Add(item);
}

}

, ,

IDisplayable {   string {get;} }

0

All Articles