2012-08-07 126 views
1

我正在处理一个ASP .net项目。我想用下面的代码加载一个控制对象中的用户控件,我试图将一个参数传递给该控件。在调试模式下,我在该行收到一条错误消息,说The file '/mainScreen.ascx?matchID=2' does not exist.。如果我删除参数,那么它工作正常。任何人都可以帮助我传递这些参数吗?有什么建议么?传递参数来控制

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

'matchID'是你控件的属性吗? – Shai 2012-08-07 11:29:46

+0

@Shai你的意思是? – user1292656 2012-08-07 11:31:14

回答

5

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

你可以做的反而是使公共财产,并赋值给它一旦控制加载:

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 

希望这会有所帮助。