简体   繁体   English

Web UserControl null 中的控件?

[英]Web Controls within UserControl null?

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.我已经构建了一个小型用户控件,它本质上是一个 DropDownList,其中包含一些基于 Target-Property 设置的预设值。

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: ASP 标记:

<%@ 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.如果我将我的选择器插入一个 aspx 页面,它就可以正常工作。 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. DropDownList“ddl”是 null 并且应用程序(逻辑上)抛出错误。 Is Page_Load the wrong Method to do such a thing? Page_Load 是错误的方法来做这样的事情吗? What am I doing wrong?我究竟做错了什么?

I should add, "ctrl" is of type dynamic, not sure if this has anything to do with it.我应该补充一点,“ctrl”是动态类型的,不确定这是否与它有关。

Thanks in advance!提前致谢!

Dennis丹尼斯

Since you're dynamically adding a user control and not a "simple" web control, you should use the LoadControl() method to instantiate it:由于您正在动态添加用户控件而不是“简单” web 控件,因此您应该使用LoadControl()方法对其进行实例化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM