GridView的删除修改

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();
    } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值