views:

32

answers:

1

Currently I'm generating UserControls as follows in an abstract base class so they are available for any other pages that implement the base class:

// doc is an XML file that may or may not contain a TopStrapline node
var pageControls = new {

           TopStrapline = (from strap in doc.Elements("TopStrapline")
                           select new TopStrapline
                                      {
                                          StraplineText =
                                              (string)strap.Attribute("text")
                                      }).FirstOrDefault(),

           // loads of other UserControls generated from other nodes
};

// if there's a StrapLine node, I want to make it available as a property 
// in this base class. Any page that needs a TopStrapline can just add the base 
// class's TopStrapline to a placeholder on the page.
if (pageControls.TopStrapline != null)
{
    this.TopStrapline = GetTopStrapline(pageControls.TopStrapline);
}

private TopStrapline GetTopStrapline(TopStrapline strapline)
{
    TopStrapline topStrapline = (TopStrapline)LoadControl("~/Path/TopStrapline.ascx");

    topStrapline.StraplineText = strapline.StraplineText;

    return topStrapline;
}

What's bugging me about this code is that I can create an instance of TopStrapline with the LinqToXML but it's no good as a user control because I need to load the UserControl with LoadControl. This works but it seems a bit clunky. Ideally I could execute LoadControl directly into the pageControls anonymous object, and then assign that loaded control into the page's property.

Is this possible? Can anyone suggest a better solution to this issue? Thanks

+1  A: 

Would this work for you?

this.TopStrapline = doc.Elements("TopStrapline")
  .Select(e => {
      var control = (TopStrapline)LoadControl("~/Path/TropStrapLine.ascx");
      control.StraplineText = e.Attribute("text");

      return control;
  }).FirstOrDefault();
Matthew Abbott
Yep, that did the trick. Thanks man.
DaveDev