שתף באמצעות


DataGridView selection through keyboard provides wrong selected row index!

Question

Wednesday, April 13, 2016 7:53 AM

I am new to programming. So if my question is immature please forgive me.

I am trying to build an application with VB.NET using Visual Studio 2010, .Net frame work is 4.0

In a window I want let my user to opt desired row through keyboard from a DataGridView control. But while selecting through keyboard it gives a wrong selectedRow index (exactly +1). However through mouse click it is perfectly correct.

I am capturing the KeyPress event of datagridview control and if it is enter key the chooses the value from selected row as below;

If Selection > 0 Then

     Dim xChoice As Object = Me.dgvId.Rows(Me.dgvId.SelectedCells(1).RowIndex).Cells(0).Value

End If

Kindly advice me resolve it.

Thanking you in advance.

SPJ

All replies (8)

Wednesday, April 13, 2016 8:09 PM ✅Answered | 2 votes

 Try using the KeyDown event of the DGV as shown below.  This seems to work fine on my end.

 You can test it in a new Form project with 1 DataGridView added to the Form.  Just remember that the Row and Column indexes are 0 based,  meaning the first row is at index 0,  not 1.  Same with the Columns.

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'this is just to set up the DGV
        DataGridView1.Columns.Add("Column0", "Column 0")
        DataGridView1.Columns.Add("Column1", "Column 1")
        DataGridView1.RowHeadersVisible = False
        DataGridView1.AllowUserToAddRows = False

        'You need to set the SelectionMode to FullRowSelect
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

        'this is just to add a few rows to the DGV for this example
        For i As Integer = 0 To 5
            DataGridView1.Rows.Add(New String() {"C0-R" & i.ToString, "C1-R" & i.ToString})
        Next
    End Sub

    Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
        If e.KeyCode = Keys.Enter Then
            e.Handled = True
            Me.Text = DataGridView1.SelectedRows(0).Index.ToString
        End If
    End Sub
End Class

If you say it can`t be done then i`ll try it


Wednesday, April 13, 2016 8:39 AM

But while selecting through keyboard it gives a wrong selectedRow index (exactly +1). However through mouse click it is perfectly correct.

Is 'Selection' the number of selected cells?  In that case, the row selected will be the row of the second selected cell - Me.dgvId.SelectedCells(1).RowIndex.    If you are expecting the row to be the first selected cell then that reference should be to the first item in the collection - Me.dgvId.SelectedCells(0).RowIndex.

Your comment ' (exactly +1)' makes this likely.

However it is also possible that the keypress event is not appropriate, because the current cell has not changed at that point.  If yo are interested in the current cell rather than the selection then the CurrentCellChanged event is more suitable. See:
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcellchanged(v=vs.110).aspx


Wednesday, April 13, 2016 9:19 AM

Hi,

How about this?
 1) handle (DataGridView).SelectionChanged
 2) loop (DataGridView).SelectedRows and get selected Row index
 3) show index or do something

This can be available with both keyboard and mouse.

sample code:

Private Sub dgvId_SelectionChanged(sender As Object, e As EventArgs) Handles dgvId.SelectionChanged
    For Each r As DataGridViewRow In Me.dgvId.SelectedRows
        Messagebox.Show("selected row = " & (r.Index + 1).ToString)
    Next r
End Sub

Regards.


Wednesday, April 13, 2016 5:39 PM

Hi,

Thank you for your response.

You are true, the 'Selection' is the number of selected cells. "Dim Selection As Int32 = dgvId.GetCellCount(DataGridViewElementStates.Selected)"

I tried changing code "Me.dgvId.SelectedCells(0).RowIndex." but doesn't work.

My DGV control is ".MultiSelect = False" also it is "ReadOnly" 

I only need, while my user press 'Enter' key on key board system has to detect the selected row.


Wednesday, April 13, 2016 7:30 PM

Hi Ashidacchi,

Thank you for your response.

In 'SelectionChanged' event it is perfectly working fine. But the value of selected row is read, while user presses the 'Enter' key in keyboard. I am capturing the 'Enter' key through 'KeyPress' event of DGV.

But while pressing 'Enter' key the selected row becomes +1


Wednesday, April 13, 2016 7:58 PM | 2 votes

Hi Ashidacchi,

Thank you for your response.

In 'SelectionChanged' event it is perfectly working fine. But the value of selected row is read, while user presses the 'Enter' key in keyboard. I am capturing the 'Enter' key through 'KeyPress' event of DGV.

But while pressing 'Enter' key the selected row becomes +1

I believe Acamar was close with his second point: "...However it is also possible that the keypress event is not appropriate, because the current cell has not changed at that point..."  Actually the problem is that the row has already changed and you need your code to execute before that happens.

Use the KeyDown event instead of KeyPress event and then your code will run before the current row changes instead of after.

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, April 14, 2016 3:02 PM

Hi IronRazerz,

Thank you for your valuable reply.

My problem is solved with "KeyDown" event and it is working fine now.

I tried "KeyDown" and "KeyUp" events even before but the error was I didn't use below line;

"e.Handled = True"

Thank you once again :) :)

SPJ


Thursday, April 14, 2016 6:33 PM

Hi IronRazerz,

Thank you for your valuable reply.

My problem is solved with "KeyDown" event and it is working fine now.

I tried "KeyDown" and "KeyUp" events even before but the error was I didn't use below line;

"e.Handled = True"

Thank you once again :) :)

SPJ

 Yes,  not setting the Handled property of the KeyEventArgs to True would be the problem you had.  Glad it helped.  8)

If you say it can`t be done then i`ll try it