第一种:使用DataSource数据源中自带的编辑删除方法,这种不常用,在这里就不加说明了。
第二种:使用GridView的三种事件:GridView1_RowEditing(编辑)、GridView1_RowUpdating(更新)、GridView1_RowCancelingEdit(取消编辑)。GridView1属性中将DataKeyNames的值设置为主键名,否则找不到索引,这个很重要哦。
该方法有2种操作,一种是不对绑定列转换为模板列,另外一种是转换为模板列。
这里先说不转换为模板列的情况;
首先;先对GridView进行数据绑定,不管用代码绑定还是DataSource绑定都可以。绑定好后,对GridView添加绑定列 和编辑列 (注意这里,添加好后不做任何改动,千万不要将它们转换为模板列),添加好后,将所要绑定的数据库表字段填入 属性中。
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{ //执行删除
string str = "delete from tb_hby where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
db.Delete(str); //db是操作类的实例,Delete是删除数据的方法
this.GridView1.DataBind();
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{//执行更新
string cell1 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();//第一列注意这种写法很重要
string cell2 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();//第二列注意这种写法很重要
string str = "update tb_hby set hby_title='" + cell1 + "',hby_Datetime='" + cell2 + "' where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
db.Update(str);//db是操作类的实例,Update是更新数据的方法
GridView1.EditIndex = -1;
GView();
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{//激活编辑按钮的事件
this.GridView1.EditIndex = e.NewEditIndex;
GView();
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{//取消编辑状态的事件
GridView1.EditIndex = -1;
GView();
}
说明:此方法中,如果要求某个绑定列不做编辑,则在它的前台代码中加入ReadOnly=”true”即可。
此方法有一些缺点,比如对日期列进行格式化时,显示的时候是格式化后的日期,但是在编辑状态下仍然显示出日期的原貌,还有,某一列的字符太长时,不好对它进行字符截取。
在点击删除按钮的时候,如果需要一个弹出删除提示,则要将删除列转化为模板列,其代码如下:
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('确定要删除吗?')" Text="删除"></asp:LinkButton>
</ItemTemplate>
也可以这样写:
在RowDataBind事件中:
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkdelete = (LinkButton)e.Row.FindControl("lnkdelete");
lnkdelete.Attributes.Add("onclick","return confirm('您确定要删除吗?')");
}
如果不转化为模板列,这这样写:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
//((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[0].Text + "\"吗?')");
((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除吗?')");
}
}
完整代码如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating">