原文发布时间为:2008-08-01 —— 来源于本人的百度文章 [由搬家工具导入]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
//gridview无数据源实现更新(断开更新)拖放一个gridview时没有编辑这个项,应该把它的属性AutoGeneraltedEditButton这个属性改成true,这样编辑这个链接就会出现
public partial class Default3 : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=test;uid=sa;pwd=123456");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Bind();
}
private void Bind()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from stu", conn);
DataSet ds = new DataSet();
sda.Fill(ds, "temp");
GridView1.DataSource = ds.Tables["temp"].DefaultView;
GridView1.DataBind();
}
private void fill(int id, string name, string banji)
{
SqlDataAdapter sda = new SqlDataAdapter("select * from stu", conn);
SqlCommandBuilder scbld = new SqlCommandBuilder(sda);//因为有这句,所以关闭连接后也能更新
DataSet ds = new DataSet();
sda.Fill(ds, "temp");
ds.Tables["temp"].DefaultView.Sort = "id";
int index = ds.Tables["temp"].DefaultView.Find(id);
ds.Tables["temp"].Rows[index]["name"] = name;
ds.Tables["temp"].Rows[index]["class"] = banji;
int rows = sda.Update(ds, "temp");
Response.Write("update " + rows + " rows datas");
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = e.RowIndex;
int id = Convert.ToInt32(GridView1.Rows[index].Cells[1].Text);
string name = ((TextBox)GridView1.Rows[index].Cells[2].FindControl("TextBox1")).Text;
string banji = ((TextBox)GridView1.Rows[index].Cells[3].FindControl("TextBox2")).Text;
fill(id, name, banji);
GridView1.EditIndex = -1;
Bind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
Bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
Bind();
}
}