How to cancel Update and Delete Operations in a GridView

I was recently asked a simple way to cancel update and delete operation in a GridView. It is quite simple to do so as shown here:

C#

protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true;
}

void gv_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
// Check if there is atleast one row left in the GridView
// before deleting
if (gv.Rows.Count <= 1)
{
e.Cancel = true;
}
}

VB.NET

Protected Sub gv_RowUpdating(ByVal sender As Object, _
ByVal e As GridViewUpdateEventArgs)
e.Cancel = True
End Sub

Private Sub
gv_RowDeleting(ByVal sender As Object, _
ByVal e As GridViewDeleteEventArgs)
' Check if there is atleast one row left in the GridView
' before deleting
If gv.Rows.Count <= 1 Then
e.Cancel = True
End If
End Sub
You can also add your own conditions before cancelling these events.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: