ASP.NET Custom Controls - Composites ASP.NET Custom Controls - Composites asp.net asp.net

ASP.NET Custom Controls - Composites


I say go ahead with the custom rendered control. I find that in most cases the composite can be easier done and used in a UserControl, but anything beyond that and you'd need to have a finer degree of control (pun unintended) to merit your own rendering strategy.

There maybe controls that are simple enough to merit a composite (e.g., a textbox combined with a javascript/dhtml based datepicker, for example) but beyond that one example, it looks like custom rendered controls are the way to go.


Here's another extension method that I use for custom rendering:

 public static void WriteControls        (this HtmlTextWriter o, string format, params object[] args) {     const string delimiter = "<2E01A260-BD39-47d0-8C5E-0DF814FDF9DC>";    var controls  = new Dictionary<string,Control>();    for(int i =0; i < args.Length; ++i)    {        var c = args[i] as Control;        if (c==null) continue;       var guid = Guid.NewGuid().ToString();       controls[guid] = c;       args[i] = delimiter+guid+delimiter;    }    var _strings = string.Format(format, args)                         .Split(new string[]{delimiter},                                StringSplitOptions.None);    foreach(var s in _strings)    {        if (controls.ContainsKey(s))            controls[s].RenderControl(o);       else            o.Write(s);    }}

Then, to render a custom composite in the RenderContents() method I write this:

protected override void RenderContents(HtmlTextWriter o){     o.WriteControls         (@"<table>               <tr>                    <td>{0}</td>                    <td>{1}</td>               </tr>             </table>"            ,Text            ,control1); }


Rob, you are right. The approach I mentioned is kind of a hybrid. The advantage of having ascx files around is that on every project I've seen, designers would feel most comfortable with editing actual markup and with the ascx you and a designer can work separately. If you don't plan on actual CSS/markup/design changes on the controls themselves later, you can go with a custom rendered control. As I said, my approach is only relevant for more complicated scenarios (and these are probably where you need a designer :))