c#
  • asp.net
  • custom-controls
  • rendering
  • 2011-07-07 68 views 2 likes 
    2

    如何使用自定義控件渲染其他控件?顯然,在渲染階段,已經太晚了。測試工作,它不包含< ASP:sometag >,但test2的是什麼,我希望能夠寫出來和渲染正確C#自定義控件渲染其他控件

    protected override void Render(HtmlTextWriter writer) 
         { 
          const string test = @"<a href='http://www.something.com'></a>"; 
          const string test2 = "<asp:HyperLink ID='HyperLink1' runat='server' NavigateUrl='www.something.com'>Some Text</asp:HyperLink>"; 
    
          writer.Write(test2); 
         } 
    

    回答

    5

    可以重寫CreateChildControls方法as shown in this example

    protected override void CreateChildControls() 
    { 
        // Add a LiteralControl to the current ControlCollection. 
        this.Controls.Add(new LiteralControl("<h3>Value: ")); 
    
        // Create a text box control, set the default Text property, 
        // and add it to the ControlCollection. 
        TextBox box = new TextBox(); 
        box.Text = "0"; 
        this.Controls.Add(box); 
    
        this.Controls.Add(new LiteralControl("</h3>")); 
    } 
    

    您可以實例化並添加HyperLink控件,而不是文字/文本框控件,例如:

    var link = new HyperLink(); 
    link.NavigateUrl = "..."; 
    link.Text = "..."; 
    this.Controls.Add(link); 
    
    +0

    完美!感謝您的快速回復! –

    相關問題