2012-08-07 127 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 

希望這會有所幫助。