1,编辑数据
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
GetData();
}
2,取消编辑
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;//取消编辑状态
GetData();
}
3,添加字段在 DataKeyNames 属性里添加显示的字段
4,取出数据库数据
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//修改数据库事件
string Cus = this.GridView1.DataKeys[e.RowIndex][0].ToString();//数据的索引
string Companys = this.GridView1.DataKeys[e.RowIndex][1].ToString();
Response.Write(Cus + "----" + Companys);//查看数据取出的数据
}
5,取出用户修改后提交上来的数据
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string Cus = this.GridView1.DataKeys[e.RowIndex][0].ToString();
string Com = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString();
string Con = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
string Title = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();//取得(客户端)单元格数据;
Response.Write(Cus + "----" + Com + "----" + Con + "----" + Title);//数据库中取得了两条数据分别赋值给了Cus和Com;
}
6,修改数据
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string Cus = this.GridView1.DataKeys[e.RowIndex][0].ToString();
string Com = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString();
string Con = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
string Title = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();//取得(客户端)单元格数据;
Update(Cus, Com, Con, Title);//(调用Update方法)执行修改操作
this.GridView1.EditIndex = -1;
GetData();//重新绑定数据
}
public void Update(string Cus, string Com, string Con, string Title)
{
SqlConnection conn = new SqlConnection("server=localhost;database=Northwind;User=sa;PassWord=");
SqlCommand com = new SqlCommand("Update Customers set CompanyName='" + Com + "',ContactName='" + Con + "',ContactTitle='" + Title + "' where CustomerID='" + Cus+"'",conn);
conn.Open();
com.ExecuteNonQuery();
conn.Close();
}
7,删除数据
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string Cus = this.GridView1.DataKeys[e.RowIndex][0].ToString();
del(Cus);
GetData();//重新绑定数据
}
public void del(string Cus)
{
SqlConnection conn = new SqlConnection("server=localhost;database=Northwind;User=sa;PassWord=");
SqlCommand com = new SqlCommand("Delete from Customers where CustomerID='" + Cus + "'", conn);
conn.Open();
com.ExecuteNonQuery();//此方法收到约束,是因为在没有删除前面的数据之前不能删除此条数据
conn.Close();
}
|