Always wanted to build an easy solution to select multiple items from an ASP.NET DataGrid and delete them all at once like hotmail does? Well, it is built in just a few simple steps. To start with, I am assuming that you are using an Access database in the backend and know how to populate DataGrid from database in ASP.NET. If not, look at my other article for beginners "Basics of Displaying Database Items on Web in ASP.NET" that will be published soon. Now, to create a selection checkbox in your data grid, first set up your data grid as you would do it normally by dragging and dropping from toolbox in to your webForm1.aspx page. Then right click on data grid and select property builder. Go to column property tab and add a template column to the list of selected columns keeping it on the top of the list. Set the header text value as Select or whatever you wish. Click OK when you are done.
DELETE * FROM tblxyz WHERE SlNo =[@SlNo];
In CommandType select Text and in parameters, add a parameter @SlNo
And for oleDBCommand2, type in Command Text as:
SELECT * FROM tblxyz ;
Now, to code behind page, i.e. in my case, it is webform1.aspx.vb, add the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim objItem As DataGridItem
    For Each objItem In DataGrid1.Items
      If objItem.ItemType ListItemType.Header And objItem.ItemType ListItemType.Footer And objItem.ItemType ListItemType.Pager Then
    Dim ChkSelected1 As Boolean
    ChkSelected1 = CType(objItem.Cells(0).FindControl("cbSelected"), CheckBox).Checked
    If ChkSelected1 = True Then
    Dim SlNo As Integer
    SlNo = DataGrid1.DataKeys(objItem.ItemIndex).ToString()
 OleDbCommand1.Parameters("@SlNo").Value = SlNo
OleDbConnection1.Open()
OleDbCommand1.ExecuteNonQuery()
OleDbConnection1.Close()
    End If
    End If
   Next
   DataGrid1.EditItemIndex = -1
   DataBind1()
   Response.Redirect("webform1.aspx")
   End Sub
   Sub DataBind1()
      Dim adp As New OleDb.OleDbDataAdapter(OleDbCommand2)
      Dim ds As New DataSet
   adp.Fill(ds)
     DataGrid1.DataSource = ds
     DataGrid1.DataBind()
   End Sub
Also, if you want to pop up a confirmation message for deletion, like in hotmail, you can add the following codes to page_load sub:
Button3.Attributes("onclick") = "return confirm('Are you sure you _wish to delete these records?');"
And, that is it. You now have a data grid with hotmail style checkboxes to select multiple records and delete them at once when you click Delete button.
No comments yet. Be the first to comment!