日期:2014-05-18 浏览次数:20444 次
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int computer_number = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); //取出要删除记录的主键值 (这里对你略作了修改,不清楚你的主键用得是啥类型,不过看number这个单词,以及常理来判断一般主键是int型) string scon = ConfigurationManager.ConnectionStrings["xmelmisConnectionString"].ConnectionString; //取出连接字符串 (其实这里多写scon变量是多余的,不过你既然这么做了么...就这样吧) string str = "delete from computer_equipment where computer_number=@computer_number"; SqlConnection conn = new SqlConnection(scon);//打造连接对象其实没必要放try里,try..catch其实是会消耗资源的,要尽量避免大段"不会发生异常的代码"往try里面扔 SqlCommand comm = new SqlCommand(str, conn); comm.Parameters.AddWithValue("@computer_number", computer_number);//AddWithValue方法,相当有用地 try { if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); //执行删除 comm.Dispose(); } catch (Exception ex) { Response.Write("数据库错误,错误原因:" + ex.Message); Response.End(); } finally { if (conn.State == ConnectionState.Open)//这句一般扔finally 块里 conn.Close(); } GridView1.EditIndex = -1; //这样也是..没必要扔try块里 gridviewBind(); }