tags:

views:

31

answers:

1

Hello all. I have a user control class like this:

///MyUserControl.ascx.cs
///.......
public partial class MyUserControl
  : UserControl
{
  //....
  public List<HyperLink> Items
  {
    get
    {
      return _Items;
    }
  }
  public string RenderControl(WebControl control)
  {
      StringBuilder sb = new StringBuilder();
      using(StringWriter stringWriter = new StringWriter(sb))
      {
        HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
        control.RenderControl(writer);
      }
      return sb.ToString();
   }
  //....
}

I want to add all Items to render tree in ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
    <%foreach (var item in Items){%>
      <div>
        <%=RenderControl(item)%>
      </div>
    <%}%>

But it's ugly solution. Does anybody know better solution?

A: 

Hey,

Any controls that you want to programmatically add you need to add to either the user control's controls collection, or add an tag to your user control and add each item the panel's controls collection as in:

foreach (var item in Items)
    panel.Controls.Add(item);

Since I think you are setting up a base user control class, you can do this by adding an abstract method in the base class:

protected abstract Control GetParentControl()

That method would be defined in MyUserControl and any class that inherits from it needs to override this method. And that way, you can use this method to return the control you want to add the items to as in:

protected void OnLoad(EventArgs e)
{
    var ctl = this.GetParentControl();
    foreach (var item in Items)
        ctl.Controls.Add(item);
}

EDIT: Or, using this approach, create a way to bind to the a control like the Repeater. Create a BindItems method that's abstract, that will pass these items to some underlying control the base class doesn't need to know about.

HTH.

Brian
Thanks for answer.But this solution doesn't fit to me because I want set each 'item' in <div>.
Dmitry Borovsky
I've edited question.
Dmitry Borovsky
I edied my response. You could add a BindItems method that's abstract, in this, you can bind to a Repeater control. The Repeater's ItemTemplate you can specify <div> around each item... Or, create a custom control that can render these items. Custom control is the typical reusable process... am I right in saying you are building a base class?
Brian