C#自定义控件来呈现其他控件

时间:2011-07-07 15:33:42

标签: c# asp.net custom-controls rendering

如何使用自定义控件渲染其他控件?显然,在渲染阶段,为时已晚。测试工作,因为它不包含< asp:sometag>,但test2是我希望能够写出并正确呈现的

 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);
        }

1 个答案:

答案 0 :(得分: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);