动态控件添加终极解决方案
动态控件添加解决方案
你可能因为动态添加的控件回传消失而苦烦过吧。
你可能因为动态添加的控件内部事件无法执行而烦过吧。
开始吧。
解决的动态控件添加问题.
做了一个示例:
新建一个类:class1.cs
我在csdn博客上,发现了这个控件。
using System.Web.UI.Design;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Xml;
using System.Collections;
using System.Web;
using System;
namespace cn.co
{
[ToolboxData("<{0}:DynamicControlsPanel runat=server></{0}:DynamicControlsPanel>")]
public class DynamicControlsPanel : Panel
{
#region 自定义的属性
[DefaultValue(HandleDynamicControls.DontPersist)]
public HandleDynamicControls ControlsWithoutIDs
{
get
{
if (ViewState["ControlsWithoutIDs"] == null)
return HandleDynamicControls.DontPersist;
else
return (HandleDynamicControls)ViewState["ControlsWithoutIDs"];
}
set { ViewState["ControlsWithoutIDs"] = value; }
}
#endregion 自定义的属性
#region 视图状态管理
protected override void LoadViewState(object savedState)
{
object[] viewState = (object[])savedState;
Pair persistInfo = (Pair)viewState[0];
foreach (Pair pair in (ArrayList)persistInfo.Second)
{
RestoreChildStructure(pair, this);
}
base.LoadViewState(viewState[1]);
}
protected override object SaveViewState()
{
if (HttpContext.Current == null)
return null;
object[] viewState = new object[2];
viewState[0] = PersistChildStructure(this, "C");
viewState[1] = base.SaveViewState();
return viewState;
}
private void RestoreChildStructure(Pair persistInfo, Control parent)
{
Control control;
string[] persistedString = persistInfo.First.ToString().Split(';');
string[] typeName = persistedString[1].Split(':');
switch (typeName[0])
{
case "C":
Type type = Type.GetType(typeName[1], true, true);
try
{
control = (Control)Activator.CreateInstance(type);
}
catch (Exception e)
{
throw new ArgumentException(String.Format("类型 '{0}' 不能恢复状态", type.
ToString()), e);
}
break;
default:
throw new ArgumentException("无法识别的类型.不能恢复状态.");
}
control.ID = persistedString[2];
switch (persistedString[0])
{
case "C":
parent.Controls.Add(control);
break;
}
foreach (Pair pair in (ArrayList)persistInfo.Second)
{
RestoreChildStructure(pair, control);
}
}
private Pair PersistChildStructure(Control control, string controlCollectionName)
{
string typeName;
ArrayList childPersistInfo = new ArrayList();
if (control.ID == null)
{
if (ControlsWithoutIDs == HandleDynamicControls.ThrowException)
throw new NotSupportedException("你必须设置你的ID");
else if (ControlsWithoutIDs == HandleDynamicControls.DontPersist)
return null;
}
typeName = "C:" + control.GetType().AssemblyQualifiedName;
string persistedString = controlCollectionName + ";" + typeName + ";" + control.ID;
if (!(control is UserControl) && !(control is CheckBoxList))
{
for (int counter = 0; counter < control.Controls.Count; counter++)
{
Control child = control.Controls[counter];
Pair pair = PersistChildStructure(child, "C");
if (pair != null)
childPersistInfo.Add(pair);
}
}
return new Pair(persistedString, childPersistInfo);
}
#endregion 视图状态管理
#region 重化控件样式
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
}
//
#endregion 重化控件样式
}
public enum HandleDynamicControls
{
DontPersist,
Persist,
ThrowException
}
}
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Xml;
using System.Collections;
using System.Web;
using System;
namespace cn.co
{
[ToolboxData("<{0}:DynamicControlsPanel runat=server></{0}:DynamicControlsPanel>")]
public class DynamicControlsPanel : Panel
{
#region 自定义的属性
[DefaultValue(HandleDynamicControls.DontPersist)]
public HandleDynamicControls ControlsWithoutIDs
{
get
{
if (ViewState["ControlsWithoutIDs"] == null)
return HandleDynamicControls.DontPersist;
else
return (HandleDynamicControls)ViewState["ControlsWithoutIDs"];
}
set { ViewState["ControlsWithoutIDs"] = value; }
}
#endregion 自定义的属性
#region 视图状态管理
protected override void LoadViewState(object savedState)
{
object[] viewState = (object[])savedState;
Pair persistInfo = (Pair)viewState[0];
foreach (Pair pair in (ArrayList)persistInfo.Second)
{
RestoreChildStructure(pair, this);
}
base.LoadViewState(viewState[1]);
}
protected override object SaveViewState()
{
if (HttpContext.Current == null)
return null;
object[] viewState = new object[2];
viewState[0] = PersistChildStructure(this, "C");
viewState[1] = base.SaveViewState();
return viewState;
}
private void RestoreChildStructure(Pair persistInfo, Control parent)
{
Control control;
string[] persistedString = persistInfo.First.ToString().Split(';');
string[] typeName = persistedString[1].Split(':');
switch (typeName[0])
{
case "C":
Type type = Type.GetType(typeName[1], true, true);
try
{
control = (Control)Activator.CreateInstance(type);
}
catch (Exception e)
{
throw new ArgumentException(String.Format("类型 '{0}' 不能恢复状态", type.
ToString()), e);
}
break;
default:
throw new ArgumentException("无法识别的类型.不能恢复状态.");
}
control.ID = persistedString[2];
switch (persistedString[0])
{
case "C":
parent.Controls.Add(control);
break;
}
foreach (Pair pair in (ArrayList)persistInfo.Second)
{
RestoreChildStructure(pair, control);
}
}
private Pair PersistChildStructure(Control control, string controlCollectionName)
{
string typeName;
ArrayList childPersistInfo = new ArrayList();
if (control.ID == null)
{
if (ControlsWithoutIDs == HandleDynamicControls.ThrowException)
throw new NotSupportedException("你必须设置你的ID");
else if (ControlsWithoutIDs == HandleDynamicControls.DontPersist)
return null;
}
typeName = "C:" + control.GetType().AssemblyQualifiedName;
string persistedString = controlCollectionName + ";" + typeName + ";" + control.ID;
if (!(control is UserControl) && !(control is CheckBoxList))
{
for (int counter = 0; counter < control.Controls.Count; counter++)
{
Control child = control.Controls[counter];
Pair pair = PersistChildStructure(child, "C");
if (pair != null)
childPersistInfo.Add(pair);
}
}
return new Pair(persistedString, childPersistInfo);
}
#endregion 视图状态管理
#region 重化控件样式
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
}
//
#endregion 重化控件样式
}
public enum HandleDynamicControls
{
DontPersist,
Persist,
ThrowException
}
}
default7.aspx页面代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>
<%@ Register Namespace="cn.co" TagPrefix="tt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem>0</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
</asp:RadioButtonList>
<tt:DynamicControlsPanel ControlsWithoutIDs=Persist runat=server ID="pan"></tt:DynamicControlsPanel>
</div>
</form>
</body>
</html>
<%@ Register Namespace="cn.co" TagPrefix="tt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem>0</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
</asp:RadioButtonList>
<tt:DynamicControlsPanel ControlsWithoutIDs=Persist runat=server ID="pan"></tt:DynamicControlsPanel>
</div>
</form>
</body>
</html>
default7.aspx.cs页面
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 Default7 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.RadioButtonList1.SelectedValue)
{
case "0":
Control con=Page.LoadControl("0.ascx");
con.ID = "dd";
this.pan.Controls.Clear();
this.pan.Controls.Add(con);
break;
case "1": Control con1 = Page.LoadControl("1.ascx");
con1.ID = "ddd";
this.pan.Controls.Clear();
this.pan.Controls.Add(con1);
break;
}
}
}
using System.Data;
using System.Configuration;
using System.Collections;
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 Default7 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.RadioButtonList1.SelectedValue)
{
case "0":
Control con=Page.LoadControl("0.ascx");
con.ID = "dd";
this.pan.Controls.Clear();
this.pan.Controls.Add(con);
break;
case "1": Control con1 = Page.LoadControl("1.ascx");
con1.ID = "ddd";
this.pan.Controls.Clear();
this.pan.Controls.Add(con1);
break;
}
}
}
还有两个o.ascx,1.ascs页面。
代码分别为
0.ascx
前台
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="0.ascx.cs" Inherits="_0" %>
0控件。<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="0控件" />
0控件。<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="0控件" />
后台
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 _0 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("0控件");
}
}
1.ascx
前台
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="1.ascx.cs" Inherits="_1" %>
1控件。<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="1控件" />
后台:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 _1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("1控件");
}
}
using System.Data;
using System.Configuration;
using System.Collections;
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 _0 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("0控件");
}
}
1.ascx
前台
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="1.ascx.cs" Inherits="_1" %>
1控件。<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="1控件" />
后台:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 _1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("1控件");
}
}
测试结果如图:
打开的页面:
当我的点击时:
当我们刷新时
结果还是
-------->
瑞气生辉(suiqirui19872005[坐断江南,笑煞之])写于:上午 10:53:32