代码如下:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class 修改数据 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 如果是为响应客户端回发而加载该页,则为 true;否则为 false。
if (!this.IsPostBack)
{
this.Bind();
}
}
/// <summary>
/// 绑定数据源数据到gridview控件
/// </summary>
private void Bind()
{
SqlConnection con = help.con();
con.Open();
string str = "select * from cs";
SqlCommand cmd = new SqlCommand(str,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
this.GridView1.DataSource = ds;
this.GridView1.DataKeyNames = new string[] { "id"};
this.GridView1.DataBind();
da.Dispose();
cmd.Dispose();
con.Close();
}
/// <summary>
/// 行编辑事件给编辑行索引赋值
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex= e.NewEditIndex;
this.Bind();
}
/// <summary>
/// 行更新前
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id= this.GridView1.DataKeys[e.RowIndex].Value.ToString();
string cate= ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[2]).Controls[0]).Text.ToString();
SqlConnection conn = help.con();
conn.Open();
string str = "update cs set Fcate='"+cate+"' where id="+id+"";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
this.GridView1.EditIndex = -1;
this.Bind();
}
/// <summary>
/// 行取消时触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;//不指向任何的行
this.Bind();
}
/// <summary>
/// 行删除前执行的事
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id= this.GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = help.con();
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from cs where id="+id+"";
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
this.GridView1.EditIndex = -1;
this.Bind();
}
/// <summary>
/// 绑定数据控件的时候给删除按钮添加脚本事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//获取第一个单元格的第二个子项
if (((LinkButton)e.Row.Cells[0].Controls[2]).Text == "删除") {
((LinkButton)e.Row.Cells[0].Controls[2]).Attributes.Add("onclick", "return confirm('确定需要删除吗?')");
}
}
}
}