读书人

asp.net动态增添TextBox控件并获取这些

发布时间: 2013-08-06 16:47:25 作者: rapoo

asp.net动态添加TextBox控件并获取这些动态添加的TextBox的Text属性
如题所示,能在服务器端实现吗?
[解决办法]
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtbx= null;
DropDownList ddl = null;

for (int i = 0; i < 4; i++)
{
txtbx= new TextBox();
txtbx.ID = "mytxt" + i;
txtbx.Text = "mytxt" + i;

pnlButton.Controls.Add(txtbx);

ddl= new DropDownList();
ddl.ID = "mydropdown " + j;
ddl.Text = "mydropdown " + j;
ddl.Items.Add("Hii");
ddl.Items.Add("Hello");
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_Click);

pnlButton.Controls.Add(ddl);

Literal lit = new Literal();
lit.Text = "</br></br>";
pnlButton.Controls.Add(lit);
}


}
[解决办法]
参考下面四篇,如果还不会,再继续讨论:
http://www.cnblogs.com/insus/archive/2012/09/24/2700658.html
http://www.cnblogs.com/insus/archive/2012/09/23/2698613.html
http://www.cnblogs.com/insus/p/3148345.html
http://www.cnblogs.com/insus/archive/2011/12/01/2270455.html
[解决办法]

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page {
protected Button btnCreate = new Button();
protected Button btnRead = new Button();
protected Label lblMessage = new Label();

protected List<string> ControlsId {
get {
if (ViewState["ControlsId"] == null) {
ViewState["ControlsId"] = new List<string>();
}
return (List<string>)ViewState["ControlsId"];
}
set { this.ViewState["ControlsId"] = value; }
}

protected override void OnLoad(EventArgs e) {
base.OnLoad(e);

btnCreate.Text = "在运行时刻添加一个按钮";
btnCreate.Click += btnCreate_Click;
this.form1.Controls.Add(btnCreate);
this.form1.Controls.Add(lblMessage);
btnRead.Text = "读取文本";
btnRead.Click += btnRead_Click;
this.form1.Controls.Add(btnRead);

foreach (string _id in ControlsId) {
TextBox _ctl = new TextBox();


_ctl.ID = _id;
this.form1.Controls.Add(_ctl);
}
}

void btnCreate_Click(object sender, EventArgs e) {
string _id = Guid.NewGuid().ToString();
ControlsId.Add(_id);
TextBox _ctl = new TextBox();
_ctl.ID = _id;
this.form1.Controls.Add(_ctl);
}

void btnRead_Click(object sender, EventArgs e) {
lblMessage.Text = "";
foreach (string _id in ControlsId) {
lblMessage.Text += ((TextBox)this.FindControl(_id)).Text;
}
}

}

读书人网 >asp.net

热点推荐