在C#中,RenderControl是一個方法,用于將Web控件的內容呈現到指定的HtmlTextWriter對象中。
以下是RenderControl方法的使用示例:
StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
Button btn = new Button();
btn.Text = "Click me";
btn.RenderControl(writer);
string renderedHtml = stringWriter.ToString();
完整示例:
using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
Button btn = new Button();
btn.Text = "Click me";
btn.RenderControl(writer);
string renderedHtml = stringWriter.ToString();
// 輸出呈現的內容
Response.Write(renderedHtml);
}
}
}
當訪問頁面時,將輸出一個按鈕的HTML代碼:
<input type="submit" name="ctl00$MainContent$btn" value="Click me" id="MainContent_btn" />