GridView 添加/删除行
.aspx
<body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="true" onrowcommand="GridView1_RowCommand"> <RowStyle BackColor="#EFF3FB" /> <Columns> <asp:TemplateField HeaderText="姓名"> <ItemTemplate> <asp:TextBox ID="txtName" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name")%>'></asp:TextBox> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAddName" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name")%>'></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="年龄"> <ItemTemplate> <asp:TextBox ID="txtAge" runat="server" Width="50px" Text='<%#DataBinder.Eval(Container,"DataItem.Age") %>'></asp:TextBox> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAddAge" runat="server" Width="50px" Text='<%#DataBinder.Eval(Container,"DataItem.Age") %>'></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Button ID="btnDel" runat="server" Text="删除" CommandName="del" CommandArgument='<%#Container.DataItemIndex %>'/> </ItemTemplate> <FooterTemplate> <asp:Button ID="btnAdd" runat="server" Text="添加" CommandName="add" /> </FooterTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#2461BF" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> </div> </form> </body>
.cs
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitTable(); } } private void InitTable() { DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Name")); dt.Columns.Add(new DataColumn("Age")); DataRow dr = dt.NewRow(); dr["Name"] = "CY"; dr["Age"] = "24"; dt.Rows.Add(dr); ViewState["dt"] = dt; this.GridView1.DataSource = dt.DefaultView; this.GridView1.DataBind(); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { DataTable dt = ViewState["dt"] as DataTable; if (e.CommandName == "add") { DataRow dr = dt.NewRow(); GridViewRow row = ((GridViewRow)((Control)e.CommandSource).Parent.Parent); dr["Name"] = (row.FindControl("txtAddName") as TextBox).Text; dr["Age"] = (row.FindControl("txtAddAge") as TextBox).Text; dt.Rows.Add(dr); } if (e.CommandName == "del") { object obj = e.CommandArgument; int index = Convert.ToInt32(e.CommandArgument); dt.Rows.RemoveAt(index); } this.GridView1.DataSource = dt.DefaultView; this.GridView1.DataBind(); }
-------------------------------------------------
大家都有这个想法,唯独拿我老猪开心。