Search code examples
c#asp.netdynamicwebformscustom-controls

Use LoadControl to programmatically load WebControl (not UserControl)


I have a custom WebControl class that represents a HyperLink surrounded by an li (list item) element. I would like to be able to load this control and add it to the page programmatically.

Here is the custom web control (ListItemHyperLink.cs):

public class ListItemHyperLink : HyperLink
{
    public string ListItemCssClass { get; set; }

    public override void RenderBeginTag(HtmlTextWriter writer)
    {
        if (!String.IsNullOrWhiteSpace(ListItemCssClass))
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, ListItemCssClass);
        }
        writer.RenderBeginTag("li");
        base.RenderBeginTag(writer);
    }

    public override void RenderEndTag(HtmlTextWriter writer)
    {
        base.RenderEndTag(writer);
        writer.RenderEndTag();
    }
}

Here is the page I am attempting to add it to (Test.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Example.Test" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <title>My Page</title>
</head>
<body>
    <form id="Form1" runat="server">
        <ul runat="server" ID="UnorderedList">
        </ul>
    </form>
</body>
</html>

And here is my attempt to load the control dynamically in the code-behind of the page (Test.aspx.cs):

public partial class Test : Page
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        var listItemHyperLink = (ListItemHyperLink) LoadControl("~/Controls/ListItemHyperLink.cs");
        listItemHyperLink.Text = "Google";
        listItemHyperLink.NavigateUrl = "http://google.com/";
        listItemHyperLink.ListItemCssClass = "li-class";
        listItemHyperLink.CssClass = "a-class";
        UnorderedList.Controls.Add(listItemHyperLink);
    }
}

When I try this, I get the following Exception:

Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Util.IWebObjectFactory'.

This exception is thrown on the line where I call LoadControl().

How can I use LoadControl() (or some other method) to use this control from code?


Solution

  • Just instantiate your custom control and add it to the Controls collection. LoadControl is for UserControls.

    var listItemHyperLink = new ListItemHyperLink();
    listItemHyperLink.Text = "Google";
    listItemHyperLink.NavigateUrl = "http://google.com/";
    listItemHyperLink.ListItemCssClass = "li-class";
    listItemHyperLink.CssClass = "a-class";
    UnorderedList.Controls.Add(listItemHyperLink);