public void getData() //取到数据,并将其绑定到gridview中
{
//SqlConnection cn = new SqlConnection("server=.; database=Northwind; user=grid; password=sa");
SqlCommand cmd = new SqlCommand("select * from Customers", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
getData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
getData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string CustomerID = this.GridView1.DataKeys[e.RowIndex][0].ToString();
string CompanyName = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString();
string ContactName = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
string Address = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();
updateCustomers(CustomerID, CompanyName, ContactName, Address);
this.GridView1.EditIndex = -1;
getData();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;
getData();
}
public void updateCustomers(string CustomerID, string CompanyName, string ContactName, string Address)
{
SqlConnection cn=new SqlConnection ("server=localhost; database=Northwind; user=grid; password=sa");
SqlCommand cmd = new SqlCommand ("update Customers set CompanyName='"+CompanyName+ "',ContactName='"+ContactName+ "',Address='"+Address +"'where CustomerID='"+CustomerID+"'",cn);
cn.Open();
cmd.ExecuteNonQuery ();
cn.Close();
}