前台代码:
class="brush:csharp;gutter:true;"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="DepartId"> <Columns> <asp:TemplateField> <HeaderTemplate> 部门编号 </HeaderTemplate> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("DepartId") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("DepartId") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> 部门名称 </HeaderTemplate> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("DepartName") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("DepartName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="操作" ShowHeader="False"> <EditItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="更新"></asp:LinkButton> <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="取消"></asp:LinkButton> </EditItemTemplate> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="编辑"></asp:LinkButton> <asp:LinkButton ID="LinkButton2" CausesValidation="false" CommandName="Delete" Text="删除" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div>
后台代码:
public partial class WebForm3 : System.Web.UI.Page { DepartmentInfoBLL dbll = new DepartmentInfoBLL(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitGridView(); } } private void InitGridView() { IList<DepartmentInfo> list = dbll.GetAll(); this.GridView1.DataSource = list; this.GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int departId = int.Parse(e.Keys[0].ToString()); //执行删除的方法 dbll.DeleteByDepartId(departId); //重新加载数据 InitGridView(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { this.GridView1.EditIndex = e.NewEditIndex; InitGridView(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = this.GridView1.Rows[e.RowIndex]; int departId = int.Parse(e.Keys[0].ToString()); string departName = (row.FindControl("TextBox2") as TextBox).Text; //执行修改的方法 dbll.Update(new DepartmentInfo() { DepartId = departId, DepartName = departName, Remark= "" }); //取消编辑状态 this.GridView1.EditIndex = -1; //重新加载一次数据 InitGridView(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { this.GridView1.EditIndex = -1; InitGridView(); } }