Reputation: 2560
I am working on an ASP .net project. I am trying to load a user control in a Control object with the following code and i am trying to pass a parameter to that control. On the debugging mode I get an error on that line saying that The file '/mainScreen.ascx?matchID=2' does not exist.
. If I remove the parameters then it works ok. Can anyone help me to pass those parameters? Any suggestions?
Control CurrentControl = Page.LoadControl("mainScreen.ascx?matchID=2");
Upvotes: 1
Views: 2847
Reputation: 5128
You cannot pass the parameter via query-string notation because user controls are simply "a building blocks" referenced by virtual path.
What you can do instead is to make a public property and assign the value to it once the control is loaded:
public class mainScreen: UserControl
{
public int matchID { get; set; }
}
// ...
mainScreen CurrentControl = (mainScreen)Page.LoadControl("mainScreen.ascx");
CurrentControl.matchID = 2;
You can now use the matchID
inside your user control like the following:
private void Page_Load(object sender, EventArgs e)
{
int id = this.matchID;
// Load control data
}
Note that the the control is participating in the page life cycle only if it's added into the page tree:
Page.Controls.Add(CurrentControl); // Now the "Page_Load" method will be called
Hope this helps.
Upvotes: 5