简体   繁体   English

使用参数动态加载用户控件

[英]Load user control dynamically with parameters

I've created a user control.我创建了一个用户控件。

public partial class Controls_pageGeneral : System.Web.UI.UserControl
{

    private int pageId;
    private int itemIndex;

    public int PageId
    {
        get { return pageId; }
        set { pageId = value; }
    }

    public int ItemIndex
    {
        get { return itemIndex; }
        set { itemIndex = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // something very cool happens here, according to the values of pageId and itemIndex
    }

}

Now I want to dynamically create this control and pass it parameters.现在我想动态创建这个控件并传递参数。 I've tried using the LoadControl function but it only has two constructor: one with string (path), and another with Type t and array of parameters.我试过使用LoadControl函数,但它只有两个构造函数:一个带有字符串(路径),另一个带有类型 t 和参数数组。

The first method works, but because of my parameters and have to use the more complicated method of LoadControl , but I don't get how to use it.第一种方法有效,但由于我的参数,必须使用更复杂的LoadControl方法,但我不知道如何使用它。 How can I case my path string of my Control to that weird object Type t?如何将我的控件的路径字符串设置为那个奇怪的对象类型 t?

In your case it's not relevant, as the second method accepts parameters passed to proper constructor, but you don't have constructor at all to your control.在您的情况下它不相关,因为第二种方法接受传递给正确构造函数的参数,但您根本没有构造函数来控制。

Just load the control using the path of the .ascx file, cast to proper type and set the properties one by one:只需使用.ascx文件的路径加载控件,转换为正确的类型并一一设置属性:

Controls_pageGeneral myControl = (Controls_pageGeneral)Page.LoadControl("path here");
myControl.PageId = 1;
myControl.ItemIndex = 2;

If you insist on using constructor, first add such:如果你坚持使用构造函数,首先添加这样的:

public Controls_pageGeneral(int pageId, int itemIndex)
{
    //code here..
}

And then:进而:

Page.LoadControl(typeof(Controls_pageGeneral), new object[] {1, 2});

Will do the same as the above as the runtime code will look for constructor accepting two integers and use it.将执行与上述相同的操作,因为运行时代码将查找接受两个整数的构造函数并使用它。

By using this approach, you will not be able to see the HTML of the UserWebControl when you add it to a container. 通过使用此方法,当您将UserWebControl添加到容器时,将无法看到它的HTML。

See here: 看这里:

http://blah.winsmarts.com/2006/05/20/loadcontrol-a-usercontrol--and-pass-in-constructor-parameters.aspx http://blah.winsmarts.com/2006/05/20/loadcontrol-a-usercontrol--and-pass-in-constructor-parameters.aspx

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

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