John
John

Reputation: 2792

Cursor inside cell datagridview vb.net

VB.NET DataGridView control:

I know this is probably super simple, but how can I put the blinking cursor inside a specific cell on form load?

I want the effect to be kind of like when you have a form with text boxes and when you set the tab order correctly, the first textbox will automatically have the focus and you can start typing right away.

On a related question: how can I make the enter key activate the form's accept button when you're inside a cell?

Thanks!

Upvotes: 0

Views: 15861

Answers (2)

Ashok Kumar
Ashok Kumar

Reputation: 1

Try this code, it will definitely work

dim strRowNumber as string

For Each row As DataGridViewRow In DataGrid.Rows

     strRowNumber = DataGrid.Rows.Count - 1
     DataGrid.CurrentCell = DataGrid.Rows(strRowNumber).Cells(1)'Cell(1) is a cell nowhich u want to edit or set focus
     DataGrid.BeginEdit(False)
Next

Upvotes: 0

Jay Riggs
Jay Riggs

Reputation: 53595

You're right, it is fairly easy to position the input cursor to a specific cell in a DataGridView. Set the DataGridView's CurrentCell property to the cell you want the cursor in and then call the DGV's BeginEdit method.

It's also easy to programmatically click (which I believe is what you mean by 'activate') a form's AcceptButton. Call the PerformClick method on the form instance's AcceptButton:

Me.AcceptButton.PerformClick()

Getting the DGV to handle the Enter key is a little trickier even though it might not seem so on the surface. The reason it is tricky is because when you have a DGV cell in edit mode, the DGV KeyPress and PreviewKeyPress events don't fire. The solution is to create your own DataGridView by extending the standard DataGridView and then overriding the ProcessCmdKey function to fire an event that tells listeners the Enter key was pressed.

Here's what your extended DGV control might look like:

Public Class MyDataGridView
    Inherits System.Windows.Forms.DataGridView

    Public Event EnterKeyPressed()

    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
        If keyData = Keys.Enter Then
            RaiseEvent EnterKeyPressed()
        End If

        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function
End Class

So assuming you're using the extended DGV above here's how you can do what you need to do:

' This positions the input cursor in the third column in the third row.
MyDataGridView1.CurrentCell = MyDataGridView1.Rows(2).Cells(2)
MyDataGridView1.BeginEdit(False)


' Be sure to wire up the EnterKeyPress event on your shiny new MyDataGridView.
Private Sub MyDataGridView1_EnterKeyPressed() Handles MyDataGridView1.EnterKeyPressed
   Me.AcceptButton.PerformClick()
End Sub

Upvotes: 1

Related Questions