How can I dynamically access user control attributes?
Im trying to create a "user control menu" where links to a page's usercontrols are开发者_Go百科 placed at the top of the page. This will allow me to put several usercontrols on a page and allow the user to jump to that section of the page without scrolling so much. In order to do this, I put each usercontrol in a folder (usercontrols) and gave each control a Description property (<%@ Control Language="C#" Description = "Vehicles" .... %>
).
My question is how can I access this description dynamically? I want to use this description as the link in my menu. So far, I have a foreach on my page that looks in the ControlCollection for a control that is of the ASP.usercontrols type. If it is I would assume that I could access its attributes and grab that description property. How can I do this? (Im also open to a better way to achieve my "user control menu", but maybe thats another question.) Should I use ((System.Web.UI.UserControl)mydynamiccontrol).Attributes.Keys
?
you can iterate over the collection and do either a switch or a few if statements
I would suggst you have an interface or an abstract base class for all your user controls:
public abstract class MyBaseClass : UserControl
{
public abstract string MyDescription {get;}
}
public MyUserControlA : MyBaseClass
{
public string MyDescription {get {return "my description";}}
}
public MyUserControlB : MyBaseClass
{
public string MyDescription {get {return "my other description";}}
}
Then you can loop over them as you do:
foreach ...
if (mydynamiccontrol is MyBaseClass)
{
Response.Write(((MyBaseClass)mydynamiccontrol).MyDescription);
}
Hope this helps
精彩评论