您的位置:首页 > 编程语言 > ASP

Asp.Net页面添加控件方法和原理

2009-06-10 10:36 736 查看
因为项目需要,如何在Asp.Net页面添加控件。

其实博客员都给出了答案,本文只是做了一些测试和总结

Asp.Net页面添加控件问题的关键就是原本在页面加载的时候所有的控件初始化操作都应该完成,动态加载将加载的过程延迟到了事件被触发之后,因此在页面回发后, 因为会有一次新的页面加载过程,显然这时候动态加载的控件是不存在的,但是用户预期的答案是显示已经加载的信息。这时候如果可能我们最好在加载的过程中进 行控件的重新加载和数据绑定。

按照一般人的思维想法,都会使用

public void AddTextBoxs()
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TextBox t = new TextBox();
t.ID = "tb" + Table1.Rows.Count;
tc1.Controls.Add(t);
TableCell tc2 = new TableCell();
DropDownList dpl = new DropDownList();
dpl.ID = "dpl" + Table1.Rows.Count;
for (int i = 0; i < 10; i++) dpl.Items.Add(i.ToString());
tc2.Controls.Add(dpl);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
Table1.Rows.Add(tr);
}

然后在一个button里添加click事件

protected void Button1_Click(object sender, EventArgs e)
{
AddTextBoxs();
}

程序测试,页面是可以生成相关的控件。

问题出在,如果你再按其他按钮会发现你添加的动态控件消失啦,更别提如何取值拉?

根据查找答案,原因是每次按钮后,页面重新post一次,必须重新添加相关的控件 所以在formload event中添加

protected void Page_Load(object sender, EventArgs e)
{

if (ViewState["Count"] != null)
{
for (int i = 0; i < Convert.ToInt16(ViewState["Count"]); i++)
AddTextBoxs();
}
}

protected void Button1_Click(object sender, EventArgs e)
{
AddTextBoxs();
if (ViewState["Count"] == null) AddButton();
ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: