开发者

Adding controls to render tree in ascx

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 HtmlTex开发者_Python百科tWriter(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜