ASP.NET上动态创建控件之绝境求生
在asp.net中动态创建一个控件总是不那么顺利,特别是当对页面的life cycle不是那么了然的情况下!这里简单描述一下要求,然后提供一个解决方案,大家看看有没有更好的idea,如果有的话就是我的大幸了,呵呵!
要求:页面上有一个add按钮,每点击一次该按钮,页面上动态创建一个webpartzone!
提醒:webpartzone只能在oninit或之前才能创建,否则报异常!
大家都知道,按钮的点击事件是在raisepostbackevent时触发的,这意味着点击事件在onload阶段之后才执行,远远落后于oninit阶段,而且viewstate在onload时才准备好,oninit以及之前的阶段根本就不能使用viewstate!如果试图在按钮点击事件里面创建webpartzone等控件,唯一的后果就是页面出错;而如果在oninit里面创建控件,由于viewstate没有准备好,那么有些数据比如当前需要创建的个数(存在viewstate里面)就无法获得!
目前对这个问题我还没有找到什么好的解决方案,经过实验,勉强得出一个不怎么优雅的方案,就是利用hiddenfield保存数据,然后直接使用request.form["xxx"]在oninit阶段取得数据;而判断是否点击按钮也是通过request.form是否存在对应数据来判断的!废话不多说了,大家看看代码吧!
(来源www.iocblog.net)
<%@ page language="c#" autoeventwireup="true" codefile="default.aspx.cs" inherits="_default" %>
<!doctype html public "-//w3c//dtd xhtml 1.1//en" "http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>untitled page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:scriptmanager id="scriptmanager1" runat="server" />
<div>
<asp:placeholder id="placeholder1" runat="server"></asp:placeholder>
<br />
<asp:button id="btnadd" runat="server" text="add" onclick="btnadd_click" />
<asp:hiddenfield id="hfcount" runat="server" value="0" />
</div>
</form>
</body>
</html>
using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
public partial class _default : system.web.ui.page
{
private int _count = 0;
protected override void oninit(eventargs e)
{
base.oninit(e);
// 取得以前已创建控件的个数
if (!string.isnullorempty(this.request["hfcount"]))
{
_count = convert.toint32(this.request["hfcount"]);
}
// 假如按下“add”按钮,那么count加一
string target = this.request["btnadd"];
if (target == "add")
{
_count++;
}
// 动态创建控件
for (int i = 0; i < _count; i++)
{ // 这里以textbox为例,实际上需要创建的是webpartzone
textbox newtextbox = new textbox();
newtextbox.id = "txt" + i.tostring();
this.placeholder1.controls.add(newtextbox);
}
}
protected void page_load(object sender, eventargs e)
{
hfcount.value = _count.tostring();
}
protected void btnadd_click(object sender, eventargs e)
{
// 不能在此添加webpartzone控件,只能在oninit或之前,否则报异常
}
}(来源www.iocblog.net)
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。