2012-02-16 122 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(); 

    } 
}