public partial class Test : System.Web.UI.Page
{
private SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=sa;database=Northwind");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
SqlDataAdapter da = new SqlDataAdapter("select * from Customers",conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Response.Write(e.Row.DataItem);
if (e.Row.Cells[0].Text.Equals("CustomerID"))
e.Row.BackColor = Color.Red;
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[3].Controls[0]).Attributes.Add("onclick","return confirm('确定要删除吗?')");
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
conn.Open();
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
string company = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
SqlCommand comm = new SqlCommand("update Customers set CompanyName = '" + company + "' where CustomerID = '"+id+"'", conn);
try
{
comm.ExecuteNonQuery();
ClientScript.RegisterClientScriptBlock(this.GetType(),"","<script>alert('更新成功')</script>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlCommand comm = new SqlCommand("delete Customers where CustomerID = '"+id+"'",conn);
conn.Open();
try
{
comm.ExecuteNonQuery();
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('删除成功')</script>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
GridView1.EditIndex = -1;
BindGrid();
}