• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 403
  • 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

                oConn.Open()
                sql.ExecuteNonQuery()
                oConn.Close()


            End If

        Next row
        gvProfiles.DataBind()
        gvdeleteemp.DataBind()
        lstbxaddmain.DataBind()
        btneditpanelclose.Focus()

    End Sub

Open in new window

0
imstac73
Asked:
imstac73
1 Solution
 
Paul JacksonCommented:
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"))
0
 
imstac73Author Commented:
Perfect, thank you.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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