So I came up with a way that I could finally dynamically load user controls, and access properties from them that I need for them to work. Here’s my post!
The Problem:
Web User Controls (.ascx files) are fantastic, because they are a breeze to set up, you can add properties, and then be on your way. They’re especially useful for controls that you really only need to use in 1 spot in the program, so it’s really hard to justify turning them into server controls.
Their biggest downside is that when you want to dynamically add them to your page, using LoadControl(“”), you have to load them as a (WebUserControl) or (Control), neither of which is useful for getting access to any custom properties you may have added.
My Idea:
In the application I’m currently working on, I have a series of controls I am working on that are “preview” listviews. They will pop-up dynamically when a user clicks an item, and they will allow them to preview the item in full detail.
The control, which is a ListView + ObjectDataSource has a property called “RecordId” that I use to set the defaultValue of my select parameters in my ObjectDataSource. I’m doing this because I want my method to only return 1 record, but as an IEnumerable, for easier databinding purposes.
Here’s the get{ } set { } of RecordId:
So you can see I’m simply setting the default value of the select parameter (in this case, the only select parameter):
So what happens when I dynamically load this control? Here’s the issue:
No RecordId in the intellisense! And if I try to compile it, it won’t work because the compiler wont let it build since it doesn’t think there is a property called RecordId.
The Solution:
Since I am going to have a whole slew of controls that require me passing in a RecordId, I came up with the idea of using inheritance to solve the problem. I created an abstract class that Inherits from a UserControl class and then added a property called RecordId:
So now, in my user control that I spoke of earlier, I will override the RecordId. Here’s the full code:
I have my user control inherit from my new abstract class, which inherits from a UserControl:
And I override the RecordId so that it’s specific to this control, and gets/sets the defaultValue of my select parameter:
So now, back in the dynamic loading page, I will cast my LoadControl(“”) to a “RecordIdUserControl” and I’ll have access to RecordId!
Fantastic! As you can see, I’m in the process of setting it to a local variable called “recordId”, which I get from a control on the page that indicates what record to load.
Conclusion:
Hopefully this helps others out there that are looking to still use a user control, but to have the added power of accessing its properties, even when you’re loading it dynamically.
Cheers!
samerpaul
Print | posted on Friday, November 13, 2009 5:18 PM