Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 constructor: 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?

like image 457
SRachamim Avatar asked Dec 04 '11 15:12

SRachamim


People also ask

How user controls are loaded dynamically?

The user control dynamically loaded at runtime is strategically placed in a table cell in the ItemTemplate . This loading takes place in the method that handles the ItemDataBound event for each row of the Repeater .


1 Answers

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.

like image 169
Shadow Wizard Hates Omicron Avatar answered Sep 25 '22 05:09

Shadow Wizard Hates Omicron