将参数传递给控件

本文关键字:控件 参数传递 | 更新日期: 2024-10-24 23:49:44

我正在做一个ASP .net项目。我正在尝试使用以下代码在 Control 对象中加载用户控件,并尝试将参数传递给该控件。在调试模式下,我在那行上收到一个错误,说The file '/mainScreen.ascx?matchID=2' does not exist..如果我删除参数,那么它可以正常工作。谁能帮我传递这些参数?有什么建议吗?

    Control CurrentControl = Page.LoadControl("mainScreen.ascx?matchID=2");

将参数传递给控件

不能通过查询字符串表示法传递参数,因为用户控件只是虚拟路径引用的"构建基块"。

相反,您可以做的是创建一个公共属性,并在加载控件后为其赋值:

public class mainScreen: UserControl
{
    public int matchID { get; set; }
}
// ...
mainScreen CurrentControl = (mainScreen)Page.LoadControl("mainScreen.ascx");
CurrentControl.matchID = 2;

现在,可以使用用户控件中的matchID,如下所示:

private void Page_Load(object sender, EventArgs e)
{
    int id = this.matchID;
    // Load control data
}

请注意,仅当控件添加到页面树中时,该控件才参与页面生命周期:

Page.Controls.Add(CurrentControl); // Now the "Page_Load" method will be called

希望这有帮助。