【问题标题】:C# custom control to render other controlsC#自定义控件呈现其他控件
【发布时间】:2011-07-07 15:33:42
【问题描述】:
如何使用自定义控件来呈现其他控件?显然,在 Render 阶段,为时已晚。测试工作,因为它不包含 ,但 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);
}
【问题讨论】:
标签:
c#
asp.net
custom-controls
rendering
【解决方案1】:
您可以覆盖 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);