-1

I am trying to use checkbox for multiple select in GridView to delete records.

Here is my Code :-

Protected Sub btnDelete_Click(sender As Object, e As EventArgs)
        Try
            'Loop through all the rows in gridview
            For Each grv As GridViewRow In GridView1.Rows
                'Finiding checkbox control in gridview for particular row
                Dim chk As CheckBox = CType(grv.FindControl("chkSelect"), CheckBox)
                If chk.Checked Then
                    'get EmpId from DatakeyNames from gridview
                    Dim empid As Integer = Convert.ToInt32(GridView1.DataKeys(grv.RowIndex).Value)
                    cmd = New SqlCommand("DeleteRecord_Sp", con)
                    cmd.Parameters.Add("@Id", SqlDbType.Int).Value = empid
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.ExecuteNonQuery()
                End If
            Next
            GridView1.EditIndex = -1
            DisplayData()
            ScriptManager.RegisterClientScriptBlock(Page, Page.[GetType](), Guid.NewGuid().ToString(), "alert('Selected Records has been deleted successfully');", True)
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Finally
            cmd.Dispose()
            con.Close()
        End Try
    End Sub

Inside Grid View :-

              <asp:CheckBox ID="chkSelect" runat="server" />
      </ItemTemplate>
    <asp:Button ID="btnDelete" runat="server" Text="Multiple Delete"
         OnClientClick="return confirm('Are you sure you want to delete selected records?')"
         OnClick="btnDelete_Click" />

I am getting error in this line :-

Dim chk As CheckBox = CType(grv.FindControl("chkSelect"), CheckBox)

Value of type 'Control' cannot be converted to 'CheckBox' in vb.net

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86

1 Answers1

0

This is because Ctype returns a collection, and not a single item

you need DirectCast to cast a single item. But since you are catching it into a variable, you do not need to at all.

Dim chk As CheckBox = grv.FindControl("chkSelect")

But you might also simply Acces it by its name. without 'finding' it, and without catching it into a variable.

If ChkSelect.Checked then

end if
  • It will take this :- ```Dim chk = DirectCast(grv.FindControl("chkSelect"), HtmlInputCheckBox)``` `````` but not taking :- ```Dim chk As CheckBox = grv.FindControl("chkSelect")``` – Akshay Makwana Mar 25 '21 at 04:51