Question

I've written a Custom User Control which returns some user specific data. To load the Custom User Control I use the following line of code:

UserControl myUC = (UserControl).Load("~/customUserControl.ascx");

But how can I access string user inside the User Control myUC?

Was it helpful?

Solution

Let's call your usercontrol "Bob"

If you Inherit from UserControl in Bob, then I guess it's safe to do this:

Bob b = (Bob).Load("~/customUserControl.ascx");

For the user part, I can't really follow what you want to do, is the "user" in the class were you create the "Bob" usercontrol and you want to set a property in the "Bob" usercontrol or is it the other way around?

For the first one you should create a property in your usercontrol.

class Bob : UserControl{
public string User { get; set;}
}

and then set it when after you create "Bob" instance.

b.User = theuser;

OTHER TIPS

Suppose your custom user control's name is "MyUserControl"

Try this code:

MyUserControl myUC = (UserControl).Load("~/customUserControl.ascx") as MyUserControl;
string result = myUC.user;

You will need to cast the loaded control to the actual type and use its public property:

MyUserControl myUCTyped = (MyUserControl)myUC;
myUCTyped.ThePublicProperty = "some value";

Thanks so far. My code is excactly the same as written above:

public partial class todo : System.Web.UI.UserControl
{
    private string mysecondteststring;
    public string setValue
    {
        get
        {
            return mysecondteststring;
        }
        set
        {
            mysecondteststring = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // my code
    }
}

But I'm not able to create an Instance of poll, in my Web Service code. Do I forget something?

--> Forgot to add the Reference to the .aspx Page, where the user control is loaded dynamically. It's working now with normal .aspx Pages. Example code can be found here

Does anyone of you know how user controls can be added in Web Services aswell, because the Reference Attribute isn't available there?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top