如何从代码后面的字符串中在网页上呈现asp.net控件?
例如,假设我有下面的aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
//want to render a text box here
</div>
</form>
</body>
</html>
我可以在我的Page_Load事件中将TextBox渲染到div中吗?
protected void Page_Load(object sender, EventArgs e)
{
//what do i do here to render a TextBox in the div from the aspx page?
}
答案 0 :(得分:2)
注意这里可能存在编译问题。但基本上是将占位符控件添加到前面的代码中 &lt;%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“Default.aspx.cs”Inherits =“nrm.FRGPproposal.Questionnaire1”%&gt;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:placeholder id="placeHolder" runat="server"/>
</div>
</form>
</body>
</html>
然后以编程方式在代码中创建一个TextBox。您需要包含System.Web.UI才能获取文本框。 然后将控件添加到placeHolder上的控件集合中。以编程方式在文本框中设置您喜欢的任何属性
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
placeHolder.Controls.Add(tb); //tb is referring to the name that you want to name your element. in this example given was TextBox. so the name of text box is tb.
}
答案 1 :(得分:0)
您还需要在Page_Init
方法中重建控件,以便在PostBack上读取控件的状态/值。
protected void Page_Init(object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
placeHolder.Controls.Add();
}