为什么要用原生的呢?
1、目的 原生出现浏览器兼容性问题 极少,不用测试多浏览兼容性 。需要考虑到市面上的其他垃圾浏览器。
2、性能不好 如果不考虑第一条 你可以换一种方式
直接上代码
.aspx页面
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DEMO</title> </head> <body> <form id="form1" runat="server"> <br /> <br /> <asp:Label ID="Label2" runat="server" Text="动态控件"></asp:Label> <asp:PlaceHolder ID="phBody" runat="server"></asp:PlaceHolder> <br /> <br /> <br /> <br /> <br /> <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="加三个动态控件" /> <asp:Button ID="btnDelLast" runat="server" OnClick="btnDelLast_Click" Text="删除后面三个" /> <br /> <br /> <br /> <br /> <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="提交保存" /> <br /> <br /> <asp:Label runat="server" ID="lbMsg" ForeColor="Red"></asp:Label> </form> </body> </html>
后台.cs代码
protected void Page_Load(object sender, EventArgs e) { #region 初始化控件 if (ViewState["AddedControl"] == null) { ViewState["AddedControl"] = 1; CreateControl(); } else { int cout = Convert.ToInt32(ViewState["AddedControl"]); for (int i = 0; i < cout; i++) { CreateControl(); } } #endregion if (!IsPostBack) { } } /// <summary> /// 给容器phBody创建动态控件 /// </summary> /// <param name="index"></param> public void CreateControl() { Panel plBody = new Panel(); TextBox txt = new TextBox(); txt.Text = ""; plBody.Controls.Add(txt); TextBox txt2 = new TextBox(); txt2.Text = ""; plBody.Controls.Add(txt2); TextBox txt3 = new TextBox(); txt3.Text = ""; plBody.Controls.Add(txt3); phBody.Controls.Add(plBody); } //获取动态添加的控件值 protected void btnSave_Click(object sender, EventArgs e) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < phBody.Controls.Count; i++) { Control ctrl = phBody.Controls[i]; for (int j = 0; j < ctrl.Controls.Count; j++) { if (j <= 3) { TextBox txt = ctrl.Controls[j] as TextBox; if (txt != null) { sb.Append(txt.Text); } } } } lbMsg.Text = sb.ToString(); } //加三行 protected void btnAdd_Click(object sender, EventArgs e) { if (ViewState["AddedControl"] == null) { ViewState["AddedControl"] = 1; } else { int cout = Convert.ToInt32(ViewState["AddedControl"]); ViewState["AddedControl"] = cout + 1; } CreateControl(); } //删除最后一行动态添加的控件 protected void btnDelLast_Click(object sender, EventArgs e) { int index = phBody.Controls.Count - 1; phBody.Controls.RemoveAt(index); if (ViewState["AddedControl"] == null) { ViewState["AddedControl"] = 0; } else { int cout = Convert.ToInt32(ViewState["AddedControl"]); ViewState["AddedControl"] = cout - 1; } }
预览效果
时间: 2024-10-11 04:02:38