12

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?

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

5 Comments

which namespace do I need to use? I'm afraid my Controls_pageGeneral is unknown to the page.
It's your class.. if it's in different web application you can't do that, otherwise just add it to your own application.
web.config can't define controls as far as I know.. where does the code behind sit?
it's in a folder in my application, when all my user controls are. but none of them are "living" on other code-behind files, though i can use them on my aspx files any where (cause I've registered them in the web.config).
If your page class got namespace, just add the same namespace to the code you posted in your question: wrap the Controls_pageGeneral class with the same namespace same way the page class is wrapped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.