UserControl中的Web控件为空? [英] Web Controls within UserControl null?
问题描述
我已经构建了一个小型用户控制,它基本上是一个DropDownList,其中包含一些基于Target-Property设置的预设值。
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.
这是代码:
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标记:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Selector.ascx.cs" Inherits="InspireClient.CustomControls.Selector" %>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
如果我将选择器插入一个aspx页面,它的工作原理很好。
示例:
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";
DropDownListddl为空,应用程序(逻辑上)抛出一个错误。 Page_Load错误的方法做这样的事情?我做错了什么?
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?
我应该添加,ctrl是动态的,不知道这是否与它有任何关系。
I should add, "ctrl" is of type dynamic, not sure if this has anything to do with it.
提前感谢
Dennis
推荐答案
由于您是动态添加用户控件而不是简单的Web控件,因此您应该使用 LoadControl()方法来实例化:
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);
}
这篇关于UserControl中的Web控件为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!