C#后台创建控件并获取值的方法
本文实例讲述了C#后台创建控件并获取值的方法。分享给大家供大家参考。具体实现方法如下:
前台代码:
<formid="form1"runat="server"> <div> <divclass="item"> Pleaseinputanumber: <asp:TextBoxrunat="server"CssClass="item"ID="txtTextCount"></asp:TextBox> <asp:Buttonrunat="server"ID="btnCreate"Text="CreateTextBoxList"ValidationGroup="CreateTextBox" OnClick="btnCreate_Click"/> <asp:Buttonrunat="server"ID="btnOK"Text="获取控件值"ValidationGroup="ShowListContent" OnClick="btnOK_Click"/> </div> <divrunat="server"id="divControls"class="item"> </div> <divrunat="server"id="divMessage"> </div> </div> </form>
后台代码:
protectedvoidPage_Load(objectsender,EventArgse) { if(this.IsPostBack) { inttxtCount=int.Parse(txtTextCount.Text);
//注意:每次PostBack时,都需要重新动态创建TextBox CreateTextBoxList(txtCount); } } ///<summary>
///Createtextboxlist ///</summary> ///<paramname="num">textboxlistcount</param> privatevoidCreateTextBoxList(intnum) { HtmlGenericControldiv; HtmlGenericControlspan; TextBoxtxt; //RegularExpressionValidatorrev;
for(inti=0;i<num;i++) { //创建div div=newHtmlGenericControl(); div.TagName="div"; div.ID="divTextBox"+i.ToString(); div.Attributes["class"]="item2";
//创建span span=newHtmlGenericControl(); span.ID="spanTextBox"+i.ToString(); span.InnerHtml="UrlAddress"+(i+1).ToString()+":";
//创建TextBox txt=newTextBox(); txt.ID="txt"+i.ToString(); txt.CssClass="input";
//创建格式验证控件,并且将其关联到对应的TextBox //rev=newRegularExpressionValidator(); //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="InvalidurlAddress!";
//添加控件到容器 div.Controls.Add(span); div.Controls.Add(txt); //div.Controls.Add(rev); divControls.Controls.Add(div); } }
protectedvoidbtnCreate_Click(objectsender,EventArgse) { txtTextCount.Enabled=false; btnCreate.Enabled=false; }
protectedvoidbtnOK_Click(objectsender,EventArgse) { TextBoxtxt; HtmlGenericControlspan; StringBuildersbResult=newStringBuilder(); inttxtCount=int.Parse(txtTextCount.Text);
//遍历获取动态创建的TextBox们中的Text值 for(inti=0;i<txtCount;i++) { //注意:这里必须通过上层容器来获取动态创建的TextBox,才能获取取ViewState内容 txt=divControls.FindControl("txt"+i.ToString())asTextBox;
if(txt!=null&&txt.Text.Trim().Length>0) { sbResult.AppendFormat("UrlAddress{0}:{1}.<br/>",i+1,txt.Text.Trim()); } } //遍历获取动态创建的TextBox们中的Text值 for(inti=0;i<txtCount;i++) { //注意:这里必须通过上层容器来获取动态创建的TextBox,才能获取取ViewState内容 span=divControls.FindControl("spanTextBox"+i.ToString())as HtmlGenericControl;
if(span!=null&&span.InnerText.Trim().Length>0) { sbResult.AppendFormat("UrlAddress{0}:{1}.<br/>",i+1,span.InnerText.Trim()); } } divMessage.InnerHtml=sbResult.ToString(); }