与参数动态加载的用户控件 [英] Load user control dynamically with parameters

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

问题描述

我创建了一个用户控件

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
    }

}

现在我想的动态创建这个控制和传递参数。
我使用LoadControl功能尝试,但它只有两个constructures:一是用绳子(路径),另一个用型T和参数数组

Now I want to dynamically create this control and pass it parameters. I've tried using the LoadControl function but it only has two constructures: 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. How can I case my path string of my Control to that weird object Type 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.

只是加载使用的.ascx 文件的路径控制,转换为正确的类型和设置的属性一一:

Just load the control using the path of the .ascx file, cast to proper type and set the properties one by one:

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..
}

和则:

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.

这篇关于与参数动态加载的用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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