views:

45

answers:

1

In a project I'm currently working for we've stumbled upon the need for several kinds of search results presentation controls. The search result are similar, but not identical. For example, in the "office search" result we might want to present the office name and location, while in the "document search" could contain document name, author and publishing date. These fields should be sortable.

My current strategy is to employ the Factory pattern and do something like this:

ISearchResult officeResults = SearchResultFactory.CreateOfficeSearchResults(data);
ISearchResult documentResults = SearchResultFactory.CreateDocumentSearchResults(data);

The problem is: I don't know how to implement the markup code. Should I just do

Controls.Add(officeResults);

in the containing page? Or is there some ASPX trickery to create generic web controls? Or maybe I'm overthinking this and just should create five classes? ;)

+1  A: 
Controls.Add(officeResults);

Is fine. You just need to ensure it's a WebControl (i.e.: it inherits from WebControl). Actually a "Control" is what's expected, but personally if I'm writing a "web control" I'll use/inherit from WebControl.

I've found it's useful adding it "twice":

Controls.Add(officeResults);   // adds the control to the page (or parent controls) object collection.
myPanel.Controls.Add(officeResults);  // adds the control to where you want it to appear.

Once to the parent control / page (in the executable structural sense), and then once to the container I want it to appear in (in the visual / physical hierarchal sense). I noticed that postbacks tended to work as expected when I did this - but it might be because I was doing something else wrong at the time. I'm sure others will correct me if I am.

I'd also advise using the INamingContainer interface (you don't need to add any code, it does it all itself at runtime).

Not sure I'd use a factory - I'm not saying it's wrong, but generally if I'm adding a control to a page (even dynamically) I'll know which one I want. TextBoxes, Buttons and Tables are WebControls and you wouldn't construct / add them via a Factory (at least not that I've ever seen it, or felt compelled to do so). If you were to use a factory wouldn't you have one factory method which worked out which WebControl to return based on an explicit parameter, or maybe based on the data passed in?

Just a thought, hope it helps.

BTW, I've done a bit of WebControl development - I'm not saying I'm a world expert but you might find some useful ideas here: (look in the "Morphfolia.Core" sln; in the Morphfolia.PublishingSystem project, WebControls folder and the Morphfolia.WebControls project).

Adrian K
Very useful advice, thanks! Didn't know about INamingContainer, it'll come in handy I'm sure :)
Bartek Tatkowski