2012-02-16 116 views
1

当我点击删除按钮时,它不会调用删除功能。谁能帮我?Gridview删除行

protected void GridViewQuestion_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 
      if (e.Row.RowType == DataControlRowType.DataRow) 
      { 
       ImageButton lb = (ImageButton)e.Row.FindControl("ImageButtonDelete"); 

       lb.Attributes.Add("onclick", "javascript:return " + 
        "confirm('Are you sure you want to delete this record " + 
        DataBinder.Eval(e.Row.DataItem, "question") + "')"); 
      } 
     } 

     protected void GridViewQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e) 
     { 
      int questionID = (int)GridViewQuestion.DataKeys[e.RowIndex].Value; 

      TopicEntity.deleteQuestion(questionID); 

      BindGridData(); 
     } 

public bool deleteQuestion(int QuestionID) 
     { 
      SqlConnection dbConnection = new SqlConnection(connectionString); 

      SqlCommand dbCommand = new SqlCommand(); 
      dbCommand.CommandText = "DELETE FROM Question [email protected]"; 
      dbCommand.Connection = dbConnection; 
      dbCommand.Parameters.AddWithValue("@QuestionID", QuestionID); 

      bool deleteSuccess = false; 

      try 
      { 
       dbConnection.Open(); 
       dbCommand.ExecuteNonQuery(); 
       deleteSuccess = true; 
      } 
      catch (Exception e) 
      { 
       throw e; 
      } 
      finally 
      { 
       dbConnection.Close(); 
      } 
      return deleteSuccess; 
     } 

回答

0

你的标记是什么样的?你应该有类似这样的东西给你的GridView:

<asp:GridView OnRowDeleted="GridViewQuestion_RowDeleting" /> 

或者,通过该方法的名字,你可能需要使用​​:

<asp:GridView OnRowDeleting="GridViewQuestion_RowDeleting" /> 

编辑

的错误是在你的SQL语句中。应该是这样的:

dbCommand.CommandText = "DELETE FROM Question where [email protected]"; 

您错过了WHERE关键字。

+0

我已经在我的GridView写这些。当我点击删除按钮有提示消息框。但它并没有从数据库中删除。 – lixi 2012-02-16 18:42:27

+0

@lixi好的,你的事件处理程序实际上已经达到了。你的问题听起来像你的事件没有发生。至于从你的数据库中删除数据,你需要发布你的'deleteQuestion()'方法的代码。没办法告诉那里发生了什么。 – 2012-02-16 18:45:04

+0

@lixi请编辑您的问题并发布该代码。 – 2012-02-16 18:47:02

0

如果问题在于点击ImageButton时Delete事件没有触发,那么您忘记在您的ImgaButton标记中添加CommandName="Delete"。另外,请确保在Page_Load你的GridView 绑定这样做内if(!IsPostBack)

0

尝试这样的:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "Delete") 
    { 
     int imageID = Convert.ToInt32(e.CommandArgument); 
     string constring = @"Server=User-PC\SQLEXPRESS;initial catalog=Student;Integrated Security=true"; 
     SqlConnection conn = new SqlConnection(constring); 
     conn.Open(); 
     string query="Delete from [student].[dbo].[ImageTable] where ID=" +imageID; 
     SqlCommand cmd = new SqlCommand(query, conn); 
     cmd.ExecuteNonQuery(); 
     this.LoadGrid(); 
     conn.Close(); 

    } 
}