C# – Web Controls within UserControl null

asp.netcdynamicpageloaduser-controls

I've built a small User Control which is essentially a DropDownList with some preset Values based on what the Target-Property is set on.

Here's the Code:

public partial class Selector : System.Web.UI.UserControl
{
    public string SelectedValue { get {return this.ddl.SelectedValue; } }
    public int SelectedIndex { get { return this.ddl.SelectedIndex; } }
    public ListItem SelectedItem { get { return this.ddl.SelectedItem; } }
    private string target;
    public string Target { get { return this.target; } set { this.target = value; } }
    protected void Page_Load(object sender, EventArgs e)
    {
        ddl.DataSource = target=="Group"?Util.GetAllGroups(Session["sessionId"].ToString()):Util.GetAllUsers(Session["sessionId"].ToString());
        ddl.DataBind();
    }
}

ASP-Markup:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Selector.ascx.cs" Inherits="InspireClient.CustomControls.Selector" %>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>

If I insert my Selector into an aspx-Page it works just fine.
Example:

<SCL:Selector Target="Group" runat="server" />

However, If I programmatically add it like this

ctrl = new Selector();
ctrl.Target = "User";

the DropDownList "ddl" is null and the application (logically) throws an error. Is Page_Load the wrong Method to do such a thing? What am I doing wrong?

I should add, "ctrl" is of type dynamic, not sure if this has anything to do with it.

Thanks in advance!

Dennis

Best Answer

Since you're dynamically adding a user control and not a "simple" web control, you should use the LoadControl() method to instantiate it:

protected void Page_Load(object sender, EventArgs e)
{
    Selector yourControl = (Selector) LoadControl("Selector.ascx");
    yourControl.Target = "User";
    Controls.Add(yourControl);
}