我正在开发一个ASP .net项目.我试图使用以下代码在Control对象中加载用户控件,我试图将参数传递给该控件.在调试模式下,我在该行上收到错误The file '/mainScreen.ascx?matchID=2' does not exist..如果我删除参数然后它可以正常工作.任何人都可以帮我传递这些参数吗?有什么建议?
Control CurrentControl = Page.LoadControl("mainScreen.ascx?matchID=2");
Run Code Online (Sandbox Code Playgroud)
您不能通过查询字符串表示法传递参数,因为用户控件只是虚拟路径引用的"构建块".
你可以做的是创建一个公共属性,并在加载控件后为其赋值:
public class mainScreen: UserControl
{
public int matchID { get; set; }
}
// ...
mainScreen CurrentControl = (mainScreen)Page.LoadControl("mainScreen.ascx");
CurrentControl.matchID = 2;
Run Code Online (Sandbox Code Playgroud)
您现在可以使用matchID用户控件内部,如下所示:
private void Page_Load(object sender, EventArgs e)
{
int id = this.matchID;
// Load control data
}
Run Code Online (Sandbox Code Playgroud)
请注意,只有将控件添加到页面树中时,控件才会参与页面生命周期:
Page.Controls.Add(CurrentControl); // Now the "Page_Load" method will be called
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
2628 次 |
| 最近记录: |