“Approve” Multiple records in a GridView

Every once in a while you have a list of records that need to be “approved by a manager.”  You could select the records via a filter, but that always gets a little cumbersome because there’s always one record you have to then individually “un-approve” in order to get it just right.

In this example we put a CheckBox on each row, allow the user to select whichever records they want to approve and then approve them with the click of a button.

1) Build your GridView and display your data. The following code only applies to the current page, so if your GridView allows paging you will want to balance between showing too many records versus showing enough records for an efficient approval process.  Make sure you set the DataKeyNames field to your Table’s Identity field.

2) Add the following row to your GridView:

        <asp:CheckBox runat="server" ID="chkApprove" />

3) Add a button to your page

 <asp:Button runat="server" ID="btnApprove" Text="Approve Selected" />

4) Add the code to iterate through the GridView records to the Button Click event.

Protected Sub btnApprove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApprove.Click
01   Try
02       For Each row As GridViewRow In grdContent.Rows
03           If row.RowType = DataControlRowType.DataRow Then
04               Dim cChk As CheckBox = CType(row.FindControl("chkApprove"), CheckBox)
05                   If cChk.Checked Then 
06                       ApproveMyRecord(grdContent.DataKeys(row.RowIndex).Value)
07                   End If
08           End If
09       Next
10   Catch ex As Exception
11      lblMsg.Text = "Approve error: " & ex.Message
12    End Try
End Sub

Lines 01, 10-12: Basic Try/Catch error trapping routine.  The lblMsg control is arbitrary.  Display errors as you see fit.
Lines 02, 03, 08, 09: We are iterating through every displayed row in the GridView and checking for DataControlRowType.DataRow rows (this will exclude header and footer rows).
Line 04: Create a CheckBox variable and assign the row checkbox to it.
Line 05, 07: Check to see if the CheckBox is checked and if not, skip it.
Line 06: This is where you run the code to approve the individual record.  Grab the record ID from the DataKeys using the RowIndex value.

You can improve this code by collecting the ID’s and sending them to a Stored Procedure as a list and reducing the number of calls to the database.

Leave a Reply

Your email address will not be published. Required fields are marked *