0

Receiving System.NullReferenceException with my code:

Private Sub dsplay()
        ds.Clear()
        dgv_tran.DataSource = ds
        da = New OleDbDataAdapter("SELECT p.prod_id, p.prod_name, b.cost_ave " & _
                                   "FROM tbl_products p " & _
                                   "INNER JOIN tbl_balance b " & _
                                   "ON p.ID = b.p_id", con)
        da.Fill(dt)
        dgv_tran.DataSource = ds
        dgv_tran.DataMember = "table1"
call dgv_tran_CellClick(Nothing,Nothing)
end sub    

Private Sub dgv_tran_CellClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgv_tran.CellClick
        Try
            Dim i As Integer = dgv_tran.CurrentRow.Index 'error starts in this line
            txtid.Text = dgv_tran.Item(0, i).Value
            txtname.Text = dgv_tran.Item(1, i).Value
            txtcost.Text = dgv_tran.Item(2, i).Value
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

My datagridview displays the data that I need, I can proceed with the project just fine when I remove the MessageBox.Show(ex.ToString) but I can't just ignore this error can I? Already spent 4hours trying to figure this one out. Any help pointing out the problem would be much appreciated.

Adrian
  • 93
  • 1
  • 9
  • Nearly all NullReference Exceptions have the same set of causes. See [NullReference Exception in Visual Basic](http://stackoverflow.com/a/26761773/1070452) for help on this. Just because they click on a cell doesnt mean that will be the current row, if `CurrentRow` is `Nothing`, you will get an NRE. Use the event args, `e.ColumnIndex` and `e.RowIndex` to know where they clicked. – Ňɏssa Pøngjǣrdenlarp May 25 '15 at 14:37
  • OK I tried removing this line **call dgv_tran_CellClick(Nothing,Nothing)** and the expected NRE didnt show up. Is this even considered good coding habit? To call event handlers and give it (Nothing, Nothing) parameters? – Adrian May 25 '15 at 15:01
  • I did not notice the `call` statement. Dont do that - events are for interacting with the user. – Ňɏssa Pøngjǣrdenlarp May 25 '15 at 15:05
  • Duly noted. You have my thanks once again sir @Plutonix – Adrian May 25 '15 at 15:14

0 Answers0