2011-11-21 36 views
1

我有一個gridview,我試圖從後面的代碼驗證。在這種情況下,確認記錄刪除。我的刪除方法工作正常,直到我添加驗證,當我執行它時,它不會觸發刪除。Gridview CommandField驗證工作,但沒有觸發Delete方法

要清楚,刪除方法正常工作,直到我添加RowDataBound驗證。

<asp:CommandField 
     ButtonType="Image" 
     ShowEditButton="true" 
     ShowDeleteButton="true" 
     ShowCancelButton="true" 
     EditImageUrl="~/Images/edit-icon.gif" 
     UpdateImageUrl="~/Images/save-icon.png" 
     CancelImageUrl="~/Images/cancel-icon.png" 
     DeleteImageUrl="~/Images/delete-icon.png" 
     /> 

以下是相關的方法。

Protected Sub usersGrid_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) 
For Each control As Control In e.Row.Cells(0).Controls 
     Dim DeleteButton As ImageButton = TryCast(control, ImageButton) 
     If DeleteButton IsNot Nothing AndAlso DeleteButton.CommandName = "Delete" Then 
      DeleteButton.OnClientClick = "return(confirm('Are you sure you want to delete this user?\nThis cannot be undone!'))" 
     End If 
    Next 
End Sub 

Protected Sub usersGrid_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) 
    Dim userID As Integer = DirectCast(usersGrid.DataKeys(e.RowIndex).Value, Integer) 

    usersGrid_Delete(userID) 
    BindData() 
End Sub 

Protected Sub usersGrid_Delete(ByVal userID As Integer) 
    Dim con As New SqlConnection(connectionString) 
    Dim cmd As New SqlCommand("MAINT_DIST_DELETE_USER", con) 
    cmd.CommandType = CommandType.StoredProcedure 
    cmd.Parameters.AddWithValue("@userID", userID) 

    Try 
     con.Open() 
     cmd.ExecuteNonQuery() 
    Catch Ex As Exception 
     Throw Ex 
    Finally 
     con.Close() 
    End Try 
End Sub 
+0

這個問題不是很清楚。當你說「它不會觸發刪除」時,會發生錯誤嗎? RowDeleting或RowDataBound事件不會觸發嗎? – jadarnel27

+0

不,沒有發生錯誤。如果我省去了RowDataBound中使用的驗證,則會按預期進行刪除。如果我離開這個方法,沒有任何反應。沒有錯誤,但刪除不會發生。 –

回答

3

您可以使用下面的代碼(我希望你知道C#足以將其翻譯成VB.NET):

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     var deleteButton = e.Row.Cells[0].Controls.OfType<ImageButton>().FirstOrDefault(btn => btn.CommandName == "Delete"); 
     if (deleteButton != null) 
     { 
      deleteButton.OnClientClick = 
       string.Format("javascript:if(confirm('Are you sure you want to delete this user? This cannot be undone!')){{ __doPostBack('{0}', 'Delete${1}');}} return false;", GridView1.UniqueID, e.Row.RowIndex); 
     } 
    } 
} 

的原因是,ImageButton控件使用onclick屬性火回傳,而你代碼完全刪除它的默認值,回發沒有發生。

+0

其實我是一個C#人被迫使用VB,所以謝謝;-) –