Search

Selecting, Confirming and Deleting Multiple Data Grid Items

0 views

Designing the Grid for Bulk Operations

When you want to give users the ability to pick several rows at once and delete them, the DataGrid must expose a way to track each row’s identity. In ASP.NET Web Forms the most common way to do that is with a hidden key column that the grid automatically keeps in a collection called DataKeys. For the classic example we’ll assume a table called tblxyz that contains a numeric auto‑increment field named SlNo. That field will serve as the primary key, so the grid will use it to identify rows that the user selects.

Start by dropping a DataGrid control onto your page in Design view. The control comes with a set of default columns, but for bulk editing you’ll want full control over what shows up. Turn AutoGenerateColumns off so the grid only renders columns you explicitly add. In the Property Explorer set AutoGenerateColumns to false, and add a TemplateColumn for the check‑box. Give the column a header such as Choose or Select – it will appear at the top of the grid and provide a checkbox for each row. Make sure this template column is the very first one so the checkboxes line up next to the data.

After adding the column, switch to the code view and insert the markup for the check‑box inside the ItemTemplate of the template column. The snippet below shows the full grid declaration. Notice the DataKeyField="SlNo" attribute – this tells the grid to keep the value of the SlNo column for every row it renders. That value becomes available later in code through DataGrid1.DataKeys[index] where index is the zero‑based row position.

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" DataKeyField="SlNo" Width="464px">
  <HeaderStyle HorizontalAlign="Center" ForeColor="White" BackColor="DarkBlue" />
  <AlternatingItemStyle BackColor="#99FFFF" />
  <Columns>
    <asp:TemplateColumn HeaderText="Select">
      <ItemTemplate>
        <asp:CheckBox id="cbSelected" runat="server" />
      </ItemTemplate>
    </asp:TemplateColumn>
    <asp:BoundColumn DataField="Field1" HeaderText="Field 1" />
    <asp:BoundColumn DataField="Field2" HeaderText="Field 2" />
  </Columns>
</asp:DataGrid>

Below the grid drop a Button control. Set its text to Delete Selected and give it an OnClick handler such as DeleteSelected_Click. The button sits above or below the grid – the exact placement depends on the visual layout of your page, but the important part is that it can trigger a server‑side event that will process the selected rows.

Now that the UI is ready, the next step is to wire up the data source. If you’re using an Access database, place two OleDbCommand controls on the page. The first command deletes a single row based on its key. The command text is DELETE FROM tblxyz WHERE SlNo = @SlNo. The second command pulls all rows for the initial data bind: SELECT * FROM tblxyz. For the delete command, make sure CommandType is set to Text and add a parameter named @SlNo of type Integer. The read command needs no parameters. When the page loads for the first time, you will call a method such as BindGrid() that fills a DataSet with the result of the read command and assigns it to the grid’s DataSource before calling DataBind(). This pattern keeps the grid in sync with the database each time the page is rendered.

Even though the example uses OleDbCommand for Access, the same pattern applies to SqlCommand or any other ADO.NET provider. The key is that the delete query takes a single key value, the grid provides that key for every selected row, and the server loops over all rows to delete each one that the user checked. By separating the UI from the data logic, the code remains clear and easy to maintain.

When working with a larger dataset, you might consider pagination. In that scenario, the DataGrid’s PageSize property controls how many rows appear per page. The DataKeyField and DataKeys collection automatically adjust to each page, so the delete logic continues to work regardless of which page the user is on. If you enable the PagerStyle of the grid, users can navigate between pages while still selecting items across pages – though that would require a more complex tracking mechanism that stores selected keys in session or view state.

All in all, the first section sets up a DataGrid that displays data, offers a checkbox column, stores the key for each row, and presents a delete button. The markup, properties, and initial data binding provide a solid foundation. The next part of the guide shows how to process the selections on the server and remove the chosen records from the database.

Implementing the Delete Logic in Code‑Behind

With the UI wired up, the heart of the bulk delete operation lives in the button’s click event. The event handler must iterate through every item that the grid rendered, check whether the checkbox is ticked, retrieve the key value from the grid’s DataKeys collection, and execute the delete command. The code below demonstrates a straightforward approach while also ensuring that the database connection is closed properly and that the grid refreshes after the operation.

First, declare a DeleteSelected_Click method in your code‑behind file. Within the method, use a For Each loop over DataGrid1.Items. For each DataGridItem, filter out the header, footer, and pager rows by checking the ItemType property; only rows that are of type Item or AlternatingItem contain data. Inside that filter, find the CheckBox control using FindControl and read its Checked state. If the box is selected, pull the key from DataGrid1.DataKeys[item.ItemIndex], convert it to an integer, and feed it into the delete command.

Because ADO.NET commands are lightweight objects, you can reuse the same OleDbCommand instance for every row. Assign the key value to the command’s parameter before calling ExecuteNonQuery(). Wrap the database operations in a Using block to ensure that the connection is opened, used, and then automatically closed even if an exception occurs. After the loop finishes, call your BindGrid() method again to refresh the DataGrid and reflect the removed rows. Optionally, redirect to the same page to clear postback data, though re‑binding is usually sufficient.

Here is a ready‑to‑copy example that follows this pattern:

Protected Sub DeleteSelected_Click(sender As Object, e As EventArgs) Handles DeleteSelected.Click
  Using conn As New OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyAccessDb").ConnectionString)
    Using cmd As New OleDbCommand("DELETE FROM tblxyz WHERE SlNo = @SlNo", conn)
      cmd.Parameters.Add("@SlNo", OleDbType.Integer)
      conn.Open()
      For Each item As DataGridItem In DataGrid1.Items
        If item.ItemType = ListItemType.Item OrElse item.ItemType = ListItemType.AlternatingItem Then
          Dim chk As CheckBox = TryCast(item.FindControl("cbSelected"), CheckBox)
          If chk IsNot Nothing AndAlso chk.Checked Then
            Dim key As Integer = Convert.ToInt32(DataGrid1.DataKeys(item.ItemIndex))
            cmd.Parameters("@SlNo").Value = key
            cmd.ExecuteNonQuery()
          End If
        End If
    Next
    conn.Close()
  End Using
  End Using
  BindGrid()
End Sub

The BindGrid() helper re‑queries the database and updates the DataGrid. Its implementation is simple:

Private Sub BindGrid()
  Using conn As New OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyAccessDb").ConnectionString)
    Using da As New OleDbDataAdapter("SELECT * FROM tblxyz", conn)
      Dim ds As New DataSet()
      da.Fill(ds)
      DataGrid1.DataSource = ds
      DataGrid1.DataBind()
    End Using
  End Using
End Sub

For an extra layer of user safety, add a JavaScript confirmation dialog to the delete button. In the page’s Page_Load event, set the button’s OnClientClick attribute to a function that returns the result of confirm(). If the user clicks Cancel, the dialog returns false and the server event is never fired. The code looks like this:

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
  If Not IsPostBack Then
    DeleteSelected.Attributes.Add("onclick", "return confirm('Are you sure you want to delete the selected records?');")
  End If
End Sub

When users confirm, the button posts back, the click handler runs, and the selected rows are deleted. If the user cancels, the page stays unchanged. This small UX improvement mirrors the behavior of large email clients where accidental deletion is mitigated by a confirmation prompt.

Edge cases such as concurrent edits or missing keys can be addressed by wrapping the delete loop in a transaction. If your application is high‑volume, consider batching deletes into a single SQL statement that deletes all selected keys at once. That reduces round‑trips to the database but requires building a comma‑separated list of keys and a query like DELETE FROM tblxyz WHERE SlNo IN (1, 2, 3). For most scenarios, however, the row‑by‑row approach described above keeps the code simple and maintainable while still delivering the expected bulk‑delete functionality.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles