Программно изменить выбор в DatagridView (.NET)

Я изучаю VB.NET.

У меня проблема с компонентом DataGridView при попытке установить значение CurrentCell. Я пытаюсь сделать это:

У меня есть DataGridView со значениями. Я хочу сделать кнопку в своих формах, и при нажатии на нее я хочу изменить выбор из текущей строки в другую. Чтобы объяснить больше, нажав кнопку "Я", я хочу, чтобы имитировать эффект щелчка мыши на DataGridview.

Надеюсь, ты поможешь мне,

Спасибо!

Ответ 1

Возможно, что-то вроде этого:

    If DataGridView1.RowCount > 0 Then

        Dim MyDesiredIndex As Integer = 0

        If DataGridView1.CurrentRow.Index < DataGridView1.RowCount - 1 Then
            MyDesiredIndex = DataGridView1.CurrentRow.Index + 1
        End If

        DataGridView1.ClearSelection()            
        DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)
        DataGridView1.Rows(MyDesiredIndex).Selected = True

    End If

Примечание 1: Возможно, эти две строки не нужны. Я не доказал это

        DataGridView1.ClearSelection()            
        DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)

Примечание 2: обратите внимание, что если мы находимся в последней строке, она переходит к первому

Ответ 2

Вам нужно установить для определенного свойства Selected Selected значение true. Я думаю, что VB будет примерно таким:

someDGV.Rows(index).Selected = True

Ответ 3

Если ваша сетка данных привязана к BindingSource, лучше изменить там положение:

Object key = Convert.ToInt32(cdr["WordList"]);
int itemFound = lexiconNamesBindingSource.Find("ID_Name", key);
lexiconNamesBindingSource.Position = itemFound;

... и вам может потребоваться завершить его:

lexiconNamesBindingSource.ResetBidings();

(Это старый поток, но я нашел его, поэтому кто-то может найти это полезным)

Ответ 4

Просто используйте методы BindingSource.MoveNext() и BindingSource.MovePrevious().

Ответ 5

Вы можете сделать это следующим образом:

If DataGridView1.CurrentRow.Index < DataGridView1.Rows.Count Then
    DataGridView1.Rows(DataGridView1.CurrentRow.Index + 1).Selected = True
End If

Ответ 6

Чтобы получить выбранную строку, вы должны использовать SelectedRows (0).Index, в отличие от CurrentRow. Потому что если вы программно сделаете строку как выбранную, то в следующий раз вы найдете 0 в CurrentRow.Index. Так было бы:

If DataGridView1.SelectedRows(0).Index < DataGridView1.RowCount - 1 Then
    MyDesiredIndex = DataGridView1.SelectedRows(0).Index + 1
End If

DataGridView1.Rows(MyDesiredIndex).Selected = True

Ответ 7

расширяя ответ выше, который является идеальным, учитывая, что я потратил на это как минимум 4 часа. и предполагая, что ваше datagridview называется dgvDevices... этот код обработает событие, в котором вы выходите, когда вы двигаетесь назад и вперед по своим строкам

Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As   System.EventArgs) Handles btnPrev.Click
    Try
        dgvDevices.ClearSelection()
        Dim currentr As Integer = dgvDevices.CurrentCell.RowIndex
        dgvDevices.CurrentCell = dgvDevices.Rows(currentr - 1).Cells(0)
        dgvDevices.Rows(currentr - 1).Selected = True
    Catch ex As Exception
        dgvDevices.CurrentCell = dgvDevices.Rows(0).Cells(0)
        dgvDevices.Rows(0).Selected = True
    End Try

End Sub

Private Sub btnForw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForw.Click
    Try
        dgvDevices.ClearSelection()
        Dim currentr As Integer = dgvDevices.CurrentCell.RowIndex
        dgvDevices.CurrentCell = dgvDevices.Rows(currentr + 1).Cells(0)
        dgvDevices.Rows(currentr + 1).Selected = True
    Catch ex As Exception
        dgvDevices.CurrentCell = dgvDevices.Rows(dgvDevices.RowCount - 1).Cells(0)
        dgvDevices.Rows(dgvDevices.RowCount - 1).Selected = True
    End Try
End Sub

Ответ 8

Помимо правильного ответа Хавьера, если вы используете BindingSource для своего datagridview, тогда лучше будет изменить выбранный элемент из источника привязки вместо использования datagridview.CurrentCell:

' Example Definitions
Dim bsExample As New BindingSource
Dim dgv As New DataGridView
dgv.DataSource = bsExample

' Example code to change current row position
Dim desiredIndex As Integer = 10
bsExample.Position = desiredIndex

Ответ 9

Private Sub DGW2_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DGW2.DataBindingComplete
    Dim mygrid As DataGridView
    mygrid = CType(sender, DataGridView)
    mygrid.ClearSelection()
End Sub

Ответ 10

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        If DataGridView1.Rows.Count - 1 > 0 Then
            For i As Integer = 0 To DataGridView1.Rows.Count - 1 Step +1
                If DataGridView1.Rows.Count - 1 > 0 Then
                    DataGridView1.Rows.RemoveAt(0)
                End If
            Next
        Else

        End If
    End Sub