• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 405
  • Last Modified:

Delete multiple rows in gridview only deleting first record

I have a gridview with a delete checkbox and backend code to delete all records with a checked checkbox when a button is clicked.  The code doesn't throw an error but only deletes the first record that is checked.  Not sure what I'm doing wrong.

Protected Sub btndeleteemp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndeleteemp.Click
        ' Looping through all the rows in the GridView

        For Each row As GridViewRow In gvdeleteemp.Rows

            Dim username As String = Page.User.Identity.Name.Split("\"c)(1).ToString()

            Dim oConn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("Marketing_ResumesConnectionString").ConnectionString)
            Dim sql As New SqlCommand("spResumeProfileDeleteEmployees")
            sql.Connection = oConn
            sql.CommandType = CommandType.StoredProcedure
            Dim checkbox As CheckBox = CType(row.FindControl("cboxDeleteEmp"), CheckBox)
            Dim profile As String = Session("profile")
            Dim employee As Integer = Convert.ToInt32(gvdeleteemp.DataKeys(0).Values("EmployeeID"))

            'Check if the checkbox is checked.

            If checkbox.Checked Then

                ' Retreive parameters to delete

                sql.Parameters.Add(New SqlParameter("@username", Data.SqlDbType.VarChar, 50))
                sql.Parameters("@username").Value = username

                sql.Parameters.Add(New SqlParameter("@profile", Data.SqlDbType.VarChar, 50))
                sql.Parameters("@profile").Value = profile

                sql.Parameters.Add(New SqlParameter("@employee", Data.SqlDbType.BigInt))
                sql.Parameters("@employee").Value = employee


            End If

        Next row

    End Sub

Open in new window

1 Solution
Paul JacksonSoftware EngineerCommented:
The line below is always returning the employee from the first row :
Dim employee As Integer = Convert.ToInt32(gvdeleteemp.DataKeys(0).Values("EmployeeID"))
change it to :
Dim employee As Integer = Convert.ToInt32(gvdeleteemp.DataKeys(row.RowIndex).Values("EmployeeID"))
imstac73Author Commented:
Perfect, thank you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now