In Visual Studio 2022 ASP.NET Web Application Project (.NET Framework) I seemed to be able to make a User Control with generics:
public class StronglyTypedListBox<T> : System.Web.UI.UserControl {
protected ListBox lst; // This line actually exists in the .ascx.designer.cs file.
// I list it here for brevity.
public GuardedList<T> Items {
/* GuardedList<T> derives from System.Collections.ObjectModel.Collection<T>.
lst.Items will be automatically populated and updated whenever Items are modified. */
get { ... }
set { ... }
}
/* Other constructs providing functionalities such as removing an item and moving an item up/down */
}
, and the .ascx markup:
<%@ Control ...... Inherits="MyProject.StronglyTypedListBox<T>" %>
<asp:ListBox id="lst" runat="server"></asp:ListBox>
<%-- Other markup providing functionalities such as removing an item and moving an item up/down --%>
To use this "generic" user control in a page, I dragged the .ascx file into the page markup (just like how we add any UserControl into a page), and changed its id to lst
.
And I moved the following line from the .aspx.designer.cs file
protected StronglyTypedListBox<T> lst;
to the .aspx.cs file and modified it as:
protected StronglyTypedListBox<OneOfMyEntityType> lst;
All above seemed to be OK in Visual Studio. No red squiggles and the project builds with no error messages. But when pressing F5 the page shows exception saying it fails parsing line 1 of the .ascx because it couldn't load the MyProject.StronglyTypedListBox<T>
type.
Is what I want to achieve with the above codes possible? If yes, what needs to be fixed?
As discussed in comments, quit generics becasue aspnet_compiler.exe simply doesn't support it. Instead have a
Type
property and leverage reflection, which is the key to the solution.For example, below is a user control containing a ListBox (named
lst
) with itsListItem
s mapped with a collection (defined asItems
property) of a specific type (defined asItemType
property). That is, theListItem
s of the ListBox are automatically populated/added/removed according toItems
, and after postbackItems
can be rebuilt from theListItem
s.And it can be used in a Page or another user control like this: