<form runat="server" id="f1"> <div runat="server" id="d"> grid view: <asp:GridView runat="server" ID="g"> </asp:GridView> </div> <asp:TextBox runat="server" ID="t" TextMode="MultiLine" Rows="20" Columns="50"></asp:TextBox> </form>
后面的代码:
public partial class ScriptTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { g.DataSource = new string[] { "a", "b", "c" }; g.DataBind(); TextWriter tw = new StringWriter(); HtmlTextWriter h = new HtmlTextWriter(tw); d.RenderControl(h); t.Text = tw.ToString(); } }
即使GridView也位于带有runat =“ server”的from标记内,仍然出现此错误。
有什么线索吗?
您正在调用GridView.RenderControl(htmlTextWriter),因此页面引发了一个异常,即服务器控件是在Form外部呈现的。
GridView.RenderControl(htmlTextWriter)
您可以通过重写VerifyRenderingInServerForm来避免执行此操作
public override void VerifyRenderingInServerForm(Control control) { /* Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. */ }
看到这里和这里。