1
votes

Hi I have a datagridview in virtual mode.

Using this code I select multiple rows if they contain a certain string:

Try
            For Each row As DataGridViewRow In DataGridView1.Rows
                If row.Cells(1).Value.ToString().Contains(TextBox1.Text) Then
                    DataGridView1.Rows(row.Index).Selected = True
                End If
            Next
        Catch
        End Try

This code works to select the rows, but then I am unable to delete any of them using the DEL key. It's almost like the rows have not fired that they are actually selected. If I ctrl-click another row that was not part of the selection group, I can then delete all the selected rows. Does this control click fire come sort of update letting the grid know what rows are selected? How can I solve this issue?

2
I cant reproduce this problem. Please can you try this with a default datagridview? - Sam Makin
Also make sure the datagridview control has focus. - Sam Makin

2 Answers

2
votes

Seems as if it was a really silly issue. I solved it by just setting focus back to the datagrid using:

  DataGridView1.Focus()
1
votes

I was able to reproduce the issue. I see that if you just hit the delete key after programmatically selecting the rows for the user on certain conditions the rows will not delete. I think ("not sure") because it doesn't know where you clicked the delete key. If you were to do something like the below, it would delete the selected records.

 Private Sub Form1_keypressed(sender As System.Object, e As System.EventArgs) Handles MyBase.KeyDown

    If Keys.E + Keys.Delete Then

        For Each rows As DataGridViewRow In DataGridView1.SelectedRows

            DataGridView1.Rows.Remove(rows)

        Next
    End If

End Sub