SRachamim SRachamim - 1 month ago 11
ASP.NET (C#) Question

Load user control dynamically with parameters

I've created a user control.

public partial class Controls_pageGeneral : System.Web.UI.UserControl
{

private int pageId;
private int itemIndex;

public int PageId
{
get { return pageId; }
set { pageId = value; }
}

public int ItemIndex
{
get { return itemIndex; }
set { itemIndex = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
// something very cool happens here, according to the values of pageId and itemIndex
}

}


Now I want to dynamically create this control and pass it parameters.
I've tried using the LoadControl function but it only has two constructures: one with string (path), and another with Type t and array of parameters.

The first method works, but because of my parameters and have to use the more complicated method of LoadControl, but I don't get how to use it. How can I case my path string of my Control to that weird object Type t?

Thank you for you help.

Answer

In your case it's not relevant, as the second method accepts parameters passed to proper constructor, but you don't have constructor at all to your control.

Just load the control using the path of the .ascx file, cast to proper type and set the properties one by one:

Controls_pageGeneral myControl = (Controls_pageGeneral)Page.LoadControl("path here");
myControl.PageId = 1;
myControl.ItemIndex = 2;

If you insist on using constructor, first add such:

public Controls_pageGeneral(int pageId, int itemIndex)
{
    //code here..
}

And then:

Page.LoadControl(typeof(Controls_pageGeneral), new object[] {1, 2});

Will do the same as the above as the runtime code will look for constructor accepting two integers and use it.

Comments