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
}
}
现在我想动态地创建这个控件并传递参数.我试过使用 LoadControl
函数,但它只有两个构造函数:一个带有字符串(路径),另一个带有类型 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 constructor: one with string (path), and another with Type t and array of parameters.
第一种方法可行,但由于我的参数,必须使用 LoadControl
更复杂的方法,但我不知道如何使用它.如何将我的 Control 的路径字符串设置为那个奇怪的对象 Type 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.
这篇关于使用参数动态加载用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用参数动态加载用户控件


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01