简体   繁体   中英

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 ... eg 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?

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM