-1

Iam trying to get DataGridView rowIndex and set it to textbox and all is well with this code

Private Sub dgv_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellContentClick
    isitxt(e.RowIndex)
    btnInsert.Enabled = False
    btnUpdate.Enabled = True
    btnDelete.Enabled = True
End Sub

and

Sub isitxt(ByVal x As Integer)
    txtIDBarang.Text = dgv.Rows(x).Cells(0).Value
    txtNamaBarang.Text = dgv.Rows(x).Cells(1).Value
    cbJenisBarang.Text = dgv.Rows(x).Cells(2).Value
    numHargaBeli.Value = dgv.Rows(x).Cells(3).Value
    numHargaJual.Value = dgv.Rows(x).Cells(4).Value
End Sub

But i got IndexOutOfRangeException when i clicked on Column Header. how can i handle it ?

2
  • Use a try/catch/finally block or test x to see if it's a valid row index Commented Jan 26, 2016 at 15:00
  • 1
    if (e.RowIndex > -1) {...} Commented Jan 26, 2016 at 15:00

2 Answers 2

1

Note, that if you use CellContentClick, the code will be executed only if the user actually aims at text content of a cell. Usually a CellClick is makes more sense.

As for your code, you can debug and see, what's in "x", when you get an error - I guess "-1"... You can handle it then. However, the reason for this should not be in your code above.

You can also set SelectionMode = FullRowSelect and do it following way:

Private Sub dgv_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellClick
  isitxt(Me.dgv.selectedRows(0).index)
  btnInsert.Enabled = False
  btnUpdate.Enabled = True
  btnDelete.Enabled = True
End Sub

Unless you want to handle the cells separately, users usually prefer the FullRowSelect mode.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use On error resume next like this :

Private Sub dgv_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellContentClick
  on error resume next
  isitxt(e.RowIndex)
  btnInsert.Enabled = False
  btnUpdate.Enabled = True
  btnDelete.Enabled = True
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.