使用参数动态加载用户控件
我已经创建了一个用户控件。
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函数,但它只有两个构造:一个是字符串(路径),另一个是类型t和参数数组。
第一种方法有效,但由于我的参数并且必须使用更复杂的LoadControl方法,但我不知道如何使用它。 如何将我的Control的路径字符串设置为奇怪的对象Type t?
谢谢你的帮助。
在你的情况下,它是不相关的,因为第二个方法接受传递给适当的构造函数的参数,但你根本没有构造函数给你的控件。
只需使用.ascx
文件的路径加载控件,转换为正确的类型并逐个设置属性:
Controls_pageGeneral myControl = (Controls_pageGeneral)Page.LoadControl("path here"); myControl.PageId = 1; myControl.ItemIndex = 2;
如果你坚持使用构造函数,首先添加如下:
public Controls_pageGeneral(int pageId, int itemIndex) { //code here.. }
然后:
Page.LoadControl(typeof(Controls_pageGeneral), new object[] {1, 2});
将与上面相同,因为运行时代码将寻找构造函数接受两个整数并使用它。
通过使用此方法,当您将UserWebControl添加到容器时,将无法看到它的HTML。
看这里: