0

i am using VS2022.net

How can I display datagridview values in textboxes?

Move by keyboard arrows

thanks in advance

here is my code

Private Sub DataGridView1_CellStateChanged(sender As Object, e As DataGridViewCellStateChangedEventArgs) Handles DataGridView1.CellStateChanged
    TxtBook.Text = DataGridView1.CurrentRow.Cells(1).Value
    TxtAuthor.Text = DataGridView1.CurrentRow.Cells(2).Value
    TxtPublisher.Text = DataGridView1.CurrentRow.Cells(3).Value
    TxtPublish.Text = DataGridView1.CurrentRow.Cells(4).Value
    txtPage.Text = DataGridView1.CurrentRow.Cells(5).Value
    TxtNote.Text = DataGridView1.CurrentRow.Cells(6).Value

End Sub
Khaled Ali
  • 13
  • 3
  • [DataGridView.SelectionChanged](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.selectionchanged?view=windowsdesktop-7.0) Event. Also, read the Remarks section to determine whether the `CurrentCellChanged` event will be more suitable for you to handle. – dr.null Apr 05 '23 at 07:03
  • it give me this error System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Windows.Forms.DataGridView.CurrentRow.get returned Nothing. – Khaled Ali Apr 05 '23 at 07:11
  • 1
    You need to do `Nothing` check. `IF DataGridView1.CurrentRow IsNot Nothing Then ..` fill the boxes with the cells values. Otherwise clear them. – dr.null Apr 05 '23 at 07:14
  • 1
    Thank you very much for your response I thank you for your valuable advice It worked for me – Khaled Ali Apr 05 '23 at 07:19
  • You have `Option Strict Off`. Please read [this](https://stackoverflow.com/questions/2454552/what-do-option-strict-and-option-explicit-do) Q&A and the similar ones. Official docs. [Option Strict Statement](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-strict-statement). – dr.null Apr 05 '23 at 07:23

1 Answers1

0
Private Sub DataGridView1_CurrentCellChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellChanged
    If DataGridView1.CurrentRow IsNot Nothing Then
        TxtBook.Text = DataGridView1.CurrentRow.Cells(1).Value
        TxtAuthor.Text = DataGridView1.CurrentRow.Cells(2).Value
        TxtPublisher.Text = DataGridView1.CurrentRow.Cells(3).Value
        TxtPublish.Text = DataGridView1.CurrentRow.Cells(4).Value
        txtPage.Text = DataGridView1.CurrentRow.Cells(5).Value
        TxtNote.Text = DataGridView1.CurrentRow.Cells(6).Value
    End If
End Sub
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Khaled Ali
  • 13
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 08 '23 at 15:46