2010-06-10 66 views
2

如何從代碼背後的字符串中渲染網頁上的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到股利?

protected void Page_Load(object sender, EventArgs e) 
{ 
    //what do i do here to render a TextBox in the div from the aspx page? 
} 

回答

2

注意這裏可能存在編譯問題。但基本上在前面的代碼中添加一個佔位符控制。
<%@頁面語言= 「C#」 AutoEventWireup = 「真」 的CodeBehind = 「Default.aspx.cs」 繼承= 「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> 
     <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. 

} 
+0

正如@Tehrab在下面建議的那樣,最好在較早的生命週期中完成,比如Page Init,而不是頁面加載。 – 2010-06-10 18:12:53

+0

你知道我怎麼可以創建一個新的TextBox對象,就像你從一個像「System.Web.UI.WebControls.TextBox」這樣的字符串做的? – 2010-06-10 18:41:26

+0

你是說你想能夠添加一個文本框合併到div中的一些字符串的中間?就像說你有字符串「輸入名稱[System.Web.UI.WebControls.TextBox]」,你想「[System.Web.UI.WebControls.TextBox]」呈現爲一個TextBox控件? – 2010-06-10 18:58:34

0

您還需要重建控制在Page_Init方法,以便在回發讀取控制狀態/值。

protected void Page_Init(object sender, System.EventArgs e) 
{ 
    TextBox tb = new TextBox(); 
    placeHolder.Controls.Add(); 
} 
2

簡單。

添加兩個屬性到您的div元素:<div runat="server" id="myDiv"></div>

然後

TextBox tb = new TextBox(); 
    this.myDiv.Controls.Add(tb); 

如果你想呈現一個自定義用戶控件,您可以使用上面的代碼

MyUserControl control = (MyUserControl)Page.LoadControl("~/My_VirtualPathToControl"); 
    this.myDiv.Controls.Add(control); 

(你必須註冊你的控制在aspx文件中)

還有一個墨水。 在Page_Load事件中執行代碼時要小心。