ASP.NET: user controls with named objects as parameters



  • I'm pulling my hair out trying to figure out how to do this. Also bear in mind that I've never really done much work with ASP.NET (yet), though I know my way around ASP, php, etc.

    I've got a master page set up, with a bunch of content pages deriving from it. No problems there. I've also created a user control to generate a navigation menu (the built-in web controls I tried couldn't be manipulated as precisely as I needed). The problem is that one of the arguments to my user control tag is the name of an object - an asp:SiteMapDataSource tag to be exact. Both tags are located within the master page's source, and look roughly like this:

    <mytag:NavMenu id="sitenav" DataSourceID="SiteMapData" runat="server"></mytag:NavMenu>
    <asp:SiteMapDataSource ID="SiteMapData" runat="server" ShowStartingNode="false" />

    (Hopefully the forum software doesn't eat the HTML.) I initially tried simply using a get/set accessor in the C# code for the user control to stuff the DataSourceID parameter value into a protected variable that holds the data source object, not realizing, of course, that it simply passes the parameters as string literals. Implicit type conversion errors ensued, not surprisingly.

    Okay, so then I tried the old Page.FindControl() method using the name of the object that's passed in. This obviously didn't work either, I'm assuming because Page refers to the rendering Page of the user control itself, and not the containing master page where the SiteMapDataSource is actually located.

    So in other words, what's considered the correct way to pass an object instantiated by another tag as a parameter in one of your user controls within the same page? I'm assuming this is ridiculously simple, but neither the rather large book I've got nor Google have been much help here.



  • Whee, figured it out. Here's what I did, for future reference.

    I was wrong about Page referring to the currently rendering canvas of the user control itself. It turns out it actually refers to the rendering context of the content page that's using the master page - or at least that's how it seems to behave. A quick call to Page.Master.FindControl(), and it was able to grab the data source control based on the ID. Success!

    However, I still can't shake the feeling that there's a more "universal" way of doing this that behaves properly no matter if the control is embedded in a content page, a master page, another user control, etc.



  • @db2 said:

    However, I still can't shake the feeling that there's a more "universal" way of doing this that behaves properly no matter if the control is embedded in a content page, a master page, another user control, etc.

     

    Not to my (admittedly somewhat shaky) knowledge.

    If the [container].FindControl method doesn't recurse properly, you can always implement it yourself :)


Log in to reply