<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" onrowcancelingedit="GridView1_RowCancelingEdit" > <Columns> <asp:BoundField DataField="ID" ReadOnly="true" HeaderText="项目编号" /> <asp:BoundField DataField="PlanID" HeaderText="计划编号" /> <asp:BoundField DataField="ProCode" HeaderText="项目状态" /> <asp:BoundField DataField="ProName" HeaderText="项目名称" /> <asp:BoundField DataField="Manager" HeaderText="负责人" /> <asp:BoundField DataField="Phone" HeaderText="联系电话" /> <asp:CommandField HeaderText="选择" ShowSelectButton="true" /> <asp:CommandField HeaderText="编辑" ShowEditButton="true" /> <asp:CommandField HeaderText="删除" ShowDeleteButton="true" /> </Columns> </asp:GridView> 代码页: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { bind(); } } protected void bind() //绑定数据源 { string sqlstr1 = "select * from project"; DataSet ds= SQLHelper.ExecuteDataSet(sqlstr1);//数据访问函数自定义 this.GridView1.DataSource = ds; this.GridView1.DataKeyNames = new string[] { "id" };//定义主要字段以便后来方便使用 this.GridView1.DataBind(); } //删除操作,利用e.RowIndex获取索引 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string sqlstr1 = "delete from project where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'"; if (SQLHelper.ExecuteNonQuery(sqlstr1) > 0) { functions.Alert("成功!"); bind(); } else { functions.Alert("Fail"); } } //编辑操作,利用e.NewEditIndex获取当前编辑行索引,要再次绑定显示编辑行的原数据 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bind(); } //编辑状态下,更新操作,利用e.RowIndex获取索引,更新完后把当前编辑索引赋值为-1,变回正常显示状态 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string sqlstr1 = "update project set id='"+GridView1.Rows[e.RowIndex].Cells[0].ToString().Trim()+"',planid='"+GridView1.Rows[e.RowIndex].Cells[1].ToString().Trim()+"',procode='"+GridView1.Rows[e.RowIndex].Cells[2].ToString().Trim()+"',proname='"+GridView1.Rows[e.RowIndex].Cells[3].ToString().Trim()+"',manager='"+GridView1.Rows[e.RowIndex].Cells[4].ToString().Trim()+"',phone='"+GridView1.Rows[e.RowIndex].Cells[5].ToString().Trim()+"' where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'"; if (SQLHelper.ExecuteNonQuery(sqlstr1) > 0) { GridView1.EditIndex = -1; functions.Alert("True"); bind(); } else { functions.Alert("False"); } }