Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 978
roman m Avatar asked Feb 03 '09 20:02

roman m


3 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);
like image 89
Jeromy Irvine Avatar answered Nov 07 '22 12:11

Jeromy Irvine


"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

like image 23
Tom Ritter Avatar answered Nov 07 '22 13:11

Tom Ritter


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

((MyControl)control).MyProperty = "blah";
like image 41
Jim Petkus Avatar answered Nov 07 '22 12:11

Jim Petkus