使用ASP.net進行開發時,因為某些需求原因,需要在頁面中動態添加控件。當然,這些控件可以是普通的Html標簽,也可以是ASP.Net獨有的服務器端控件。關於動態寫入Html標簽控件,大家都熟悉,這裡就不再表述。本文討論的重點是:如何動態寫入服務器端控件,並且在頁面PostBack到Server端時,在Server端來獲取被動態寫入的服務器端控件的各種屬性。
這裡,我來通過一個Demo來說明這個應用。
需求:
1. 用戶在UI上輸入一個數值(比如:5),系統動態為用戶加載這個數值的Url Address輸入域;
2. 用戶輸入的Url Address內容需要通過Url格式驗證;
3. 用戶提交輸入內容後,系統給出提交的結果
設計如下:
1. CSS樣式設置:
以下為引用的內容:
<style type="text/CSS">
.item { margin:10px; border-bottom:solid 1px #CCC; } .item2 { margin:5px; } .input { width:200px; } </style> 2.前台頁面代碼: <div> <div class="item"> Please input a number: <ASP:TextBox runat="server" CSSClass="item"ID="txtTextCount"></ASP:TextBox> <ASP:RequiredFIEldValidatorID="RequiredFIEldValidator1" runat="server"ControlToValidate="txtTextCount" ValidationGroup="CreateTextBox"Display="Dynamic" ErrorMessage="Required to input content!"></ASP:RequiredFIEldValidator> <ASP:RegularExpressionValidatorID="RegularExpressionValidator1" ControlToValidate="txtTextCount"ValidationGroup="CreateTextBox" Display="Dynamic" runat="server" ErrorMessage="Only number is valid!" ValidationExpression="^\d+$"></ASP:RegularExpressionValidator> <ASP:Button runat="server" ID="btnCreate"Text="Create TextBox List" ValidationGroup="CreateTextBox" onclick="btnCreate_Click" /> <ASP:Button runat="server" ID="btnOK" Text="Get TextBox Content" ValidationGroup="ShowListContent" onclick="btnOK_Click" /> </div> <div runat="server" id="divControls" class="item"></div> <div runat="server" id="divMessage"> </div> </div>2. 前台頁面代碼:
以下為引用的內容:
<div>
<div class="item"> Please input a number: <ASP:TextBox runat="server" CSSClass="item"ID="txtTextCount"></ASP:TextBox> <ASP:RequiredFIEldValidatorID="RequiredFIEldValidator1" runat="server"ControlToValidate="txtTextCount" ValidationGroup="CreateTextBox"Display="Dynamic" ErrorMessage="Required to input content!"></ASP:RequiredFIEldValidator> <ASP:RegularExpressionValidatorID="RegularExpressionValidator1" ControlToValidate="txtTextCount"ValidationGroup="CreateTextBox" Display="Dynamic" runat="server" ErrorMessage="Only number is valid!" ValidationExpression="^\d+$"></ASP:RegularExpressionValidator> <ASP:Button runat="server" ID="btnCreate"Text="Create TextBox List" ValidationGroup="CreateTextBox" onclick="btnCreate_Click" /> <ASP:Button runat="server" ID="btnOK" Text="Get TextBox Content" ValidationGroup="ShowListContent" onclick="btnOK_Click" /> </div> <div runat="server" id="divControls" class="item"></div> <div runat="server" id="divMessage"> </div> </div>說明, 動態創建的TextBox們將裝載到divControls中。
3. 後台代碼:
以下為引用的內容:
///<summary>
/// Create textbox list ///</summary> ///<param name="num">textbox list count</param> private void CreateTextBoxList(int num) { HtmlGenericControl div; HtmlGenericControl span; TextBox txt; RegularExpressionValidator rev; for (int i = 0; i < num; i++) { //創建div div = new HtmlGenericControl(); div.TagName = "div"; div.ID = "divTextBox" + i.ToString(); div.Attributes["class"] = "item2"; //創建span span = new HtmlGenericControl(); span.ID = "spanTextBox" + i.ToString(); span.InnerHtml = "Url Address" + (i+1).ToString() +":"; //創建TextBox txt = new TextBox(); txt.ID = "txt" + i.ToString(); txt.CSSClass = "input"; //創建格式驗證控件,並且將其關聯到對應的TextBox rev = new RegularExpressionValidator(); rev.ID = "rev" + i.ToString(); rev.ControlToValidate = txt.ID; rev.Display = ValidatorDisplay.Dynamic; rev.ValidationGroup = "ShowListContent"; rev.ValidationExpression = @"(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"; rev.ErrorMessage = "Invalid url Address!"; //添加控件到容器 div.Controls.Add(span); div.Controls.Add(txt); div.Controls.Add(rev); divControls.Controls.Add(div); } } protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { int txtCount = int.Parse(txtTextCount.Text); // 注意:每次PostBack時,都需要重新動態創建TextBox CreateTextBoxList(txtCount); } } protected void btnCreate_Click(object sender, EventArgs e) { txtTextCount.Enabled = false; btnCreate.Enabled = false; } protected void btnOK_Click(object sender, EventArgs e) { TextBox txt; StringBuilder sbResult = new StringBuilder() ; int txtCount = int.Parse(txtTextCount.Text); //遍歷獲取動態創建的TextBox們中的Text值 for (int i = 0; i < txtCount; i++) { //注意:這裡必須通過上層容器來獲取動態創建的TextBox,才能獲取取VIEwState內容 txt = divControls.FindControl("txt" + i.ToString())as TextBox; if (txt != null && txt.Text.Trim().Length > 0) { sbResult.AppendFormat("Url Address{0}: {1}.<br />", i+1, txt.Text.Trim()); } } divMessage.InnerHtml = sbResult.ToString(); }4. 效果圖: