当前位置: 代码迷 >> ASP.NET >> gridview删除事件有关问题(内附代码)
  详细解决方案

gridview删除事件有关问题(内附代码)

热度:5052   发布时间:2013-02-25 00:00:00.0
gridview删除事件问题(内附代码)
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
  string computer_number = GridView1.DataKeys[e.RowIndex].Values[0].ToString(); //取出要删除记录的主键值
  string scon = ConfigurationManager.ConnectionStrings["xmelmisConnectionString"].ConnectionString; //取出连接字符串
  string str = "delete from computer_equipment where computer_number='" + computer_number + "'";

  try
  {
  SqlConnection conn = new SqlConnection(scon); //创建连接对象
  if (conn.State.ToString() == "Closed")
  conn.Open();
  SqlCommand comm = new SqlCommand(str, conn);
  comm.ExecuteNonQuery(); //执行删除
  comm.Dispose();
  if (conn.State.ToString() == "Open")
  conn.Close();

  GridView1.EditIndex = -1;
  gridviewBind();
  }
  catch (Exception ex)
  {
  Response.Write("数据库错误,错误原因:" + ex.Message);
  Response.End();
  }

  }


调试后发现点删除没反应,到底哪里出错了

------解决方案--------------------------------------------------------
对楼主的代码略做了修改,也不知道能不能成,有个老问题还是要提SQL语句别去用拼接啊....标签这样的控件也罢了,要是文本框就惨咯......
C# code
    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();    }