用户控件空内Web控件? [英] Web Controls within UserControl null?

查看:139
本文介绍了用户控件空内Web控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个小的用户控件基本上是基于什么样的目标,属性设置一些preSET值一个DropDownList。

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.

这里的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-标记:

ASP-Markup:

<%@ 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";

DropDownList的DDL为空和应用程序(逻辑)抛出一个错误。是的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.

在此先感谢!

丹尼斯

推荐答案

既然你动态添加用户控件,而不是一个简单的网络控制,你应该使用的 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);
}

这篇关于用户控件空内Web控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆