请问怎样在页面上保存一个动态生成的控件

chookrib 2004-04-26 05:49:47
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
for(int i = 0; i < 3; i ++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
this.Panel1.Controls.Add(txt);
}
}
}

private void Button1_Click(object sender, System.EventArgs e)
{
string str = "";
for(int i = 0; i < 3; i ++)
{
TextBox txt = (TextBox)Panel1.FindControl("txt" + i);
str += "第" + i.ToString() + "个文本框的值为:" + txt.Text + "<br>";
}
this.Label1.Text = str;
}

如上程序,在页面第一次打开时生成三个 TextBox,然后点击按钮后在Label中显示三个文本框的值,可每次在我点击按钮后那三个 TextBox就没有了,要怎么才能在页面上保存这些动态生成的控件,或有什么别的变通的方法?多谢!
...全文
42 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
PCXGG 2004-04-26
  • 打赏
  • 举报
回复
if(!Page.IsPostBack)
{
for(int i = 0; i < 3; i ++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
this.Panel1.Controls.Add(txt);
}
}
改为:


for(int i = 0; i < 3; i ++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
this.Panel1.Controls.Add(txt);
}
wacle 2004-04-26
  • 打赏
  • 举报
回复
<script language="c#" runat="server">
TextBox txt1=new TextBox();
TextBox txt2=new TextBox();

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!this.IsPostBack)
{
this.EnsureChildControls();
txt1.Text="hello";
this.EnsureChildControls();
txt2.Text="world";
}
}

protected override void CreateChildControls()
{
pnl1.Controls.Add(txt1);
pnl1.Controls.Add(txt2);
}
</script>
bitsbird 2004-04-26
  • 打赏
  • 举报
回复
回送后不执行!IsPostBack里的代码
goody9807 2004-04-26
  • 打赏
  • 举报
回复
去掉if(!Page.IsPostBack)
让页面每次执行时都生成

你为什么自动生成

或者你把TextBox开始隐藏点按钮时显示出来
CMIC 2004-04-26
  • 打赏
  • 举报
回复
private void Page_Load(object sender, System.EventArgs e)
{
for(int i = 0; i < 3; i ++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
this.Panel1.Controls.Add(txt);
}
}

private void Button1_Click(object sender, System.EventArgs e)
{
string str = "";
for(int i = 0; i < 3; i ++)
{
TextBox txt = (TextBox)Panel1.FindControl("txt" + i);
str += "第" + i.ToString() + "个文本框的值为:" + txt.Text + "<br>";
}
this.Label1.Text = str;
}
goody9807 2004-04-26
  • 打赏
  • 举报
回复
去掉if(!Page.IsPostBack)
让页面每次执行时都生成

你为什么自动生成

或者你把TextBox开始隐藏点按钮时显示出来
活靶子哥哥 2004-04-26
  • 打赏
  • 举报
回复
你的代码在
if(!Page.IsPostBack)内
这里的代码只在页面第一次加载的时候才执行的
提交后Page.IsPostBack就是true就不执行你写的代码了
erist 2004-04-26
  • 打赏
  • 举报
回复
if(!Page.IsPostBack)
{
for(int i = 0; i < 3; i ++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
this.Panel1.Controls.Add(txt);
}
}


改为


for(int i = 0; i < 3; i ++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
this.Panel1.Controls.Add(txt);
}

62,254

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧