Set properties on dynamically added UserControl

I'm dynamically adding a custom user control to the page as per this post.

However, i need to set a property on the user control as i add it to the page. How do I do that?

Code snippet would be nice :)

Details:

I have a custom user control with a public field (property ... e.g. public int someId;)

As I add a UserControl to a page, its type is UserControl. Do i just cast it into MyCustomUCType and set a property on a cast control?

p.s. looks like I've answered my own question after all.

Answers


Ah, I answered before you added the additional clarification. The short answer is, yes, just cast it as your custom type.

I'll leave the rest of my answer here for reference, though it doesn't appear you'll need it.


Borrowing from the code in the other question, and assuming that all your User Controls can be made to inherit from the same base class, you could do this.

Create a new class to act as the base control:

public class MyBaseControl : System.Web.UI.UserControl
{
    public string MyProperty 
    {
        get { return ViewState["MyProp"] as string; }
        set { ViewState["MyProp"] = value; }
    }
}

Then update your user controls to inherit from your base class instead of UserControl:

public partial class SampleControl2 : MyBaseControl
{
    ....

Then, in the place where you load the controls, change this:

UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);

to:

MyBaseControl uc = (MyBaseControl)LoadControl(controlPath);
uc.MyProperty = "foo";
PlaceHolder1.Controls.Add(uc);

"As I add a UserControl to a page, its type is UserControl. Do i just cast it into MyCustomUCType and set a property on a cast control?"

That's what I'd do. If you're actually using the example code where it loads different controls, I'd use an if(x is ControlType) as well.

if(x is Label)
{    
     Label l = x as Label;
     l.Text = "Batman!";
}
else
     //...

Edit: Now it's 2.0 compatible


Yes, you just cast the control to the proper type. EX:

((MyControl)control).MyProperty = "blah";

Need Your Help

What is the difference between class and styleClass attributes in JSF?

jsf jsf-2 java-ee-7

I see, that in JSF most of the standard components that mapped to HTML tags, e.g. <h:commandButton/>, have attributes class and styleClass. But no matter, which one I use, both is rendered as...

encrypt and encode URL parameters spring mvc

java encryption

I am writing a Spring mvc app and it needs to send an email with a link and encrypted params. The user will click on the link and I need to decrypt the params in the new page. So I am writing a util