views:

1314

answers:

3

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.

A: 

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

((MyControl)control).MyProperty = "blah";
Jim Petkus
This doesn't work in web site projects with user controls
John Sheehan
it works just fine.
roman m
It works if you register the control in the page.
Jim Petkus
That should be ((MyControl)control).MyProperty = "blah";
Khb
+2  A: 

"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

Tom Ritter
as good as the answer is, looks like you using 3.5 framework, mine is 2.0. thanx.
roman m
just change the var to Label and you'll be compat with 2.0
John Sheehan
+4  A: 

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);
Jeromy Irvine
I thought this only worked in web application projects and not web site projects. Is that still the case?
John Sheehan
It should work, regardless. I've never had a problem with it.
Jeromy Irvine