Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have an error('Object reference not set to an instance of an object.) on DGV Cell click events. My DGV has Computed coloums, I know that is the reason for this error but I do not know how to fix it. Therefor I am writing here. FYI, this app is for my personal use and training.

What I have tried:

Private Sub DGV_Trans_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV_Trans.CellClick

      If e.RowIndex >= 0 Then

               Dim row As DataGridViewRow
               row = Me.DGV_Trans.Rows(e.RowIndex)

           TransIDTextBox.Text = row.Cells(1).Value.ToString
               CheckBox1.Checked = row.Cells(2).Value
               SymbolTextBox.Text = row.Cells(3).Value.ToString
               QuantityTextBox.Text = row.Cells(4).Value.ToString
               PriceTextBox.Text = row.Cells(5).Value.ToString
               DTP1.Value = row.Cells(6).Value
               TxtFee.Text = row.Cells(7).Value.ToString
               TxtVat.Text = row.Cells(8).Value.ToString

       End If

   End Sub
Posted
Updated 17-May-20 20:27pm
Comments
[no name] 16-May-20 10:07am    
Which Cell is the problem? And you are aware that also for Cells the index starts at zero and the max. index will be "No of Cells - 1"?
qulaitks 16-May-20 10:13am    
The computed cell is cell(9), when I click the DGV the rows 1 to 8 values suppose to show in the related textboxs
[no name] 16-May-20 10:16am    
And index is not the problem? I mean in case you have 10 Columns the range to address them is row.Cells(0) up to row.Cells(9)
qulaitks 16-May-20 10:20am    
Cell(0) is holding the ID which is auto generated
F-ES Sitecore 16-May-20 10:34am    
Doesn't vb have 1-based indexes?

1 solution

Please, read comments in code block:
VB.NET
'try to get current row
Dim row As DataGridViewRow = Me.DGV_Trans.CurrentRow 
If row is Nothing Then Return 'or Exit Sub
'further instructions here
TransIDTextBox.Text = row.Cells(1).Value.ToString() 'second column
CheckBox1.Checked = row.Cells(2).Value '3. column
SymbolTextBox.Text = row.Cells(3).Value.ToString() '4. column
QuantityTextBox.Text = row.Cells(4).Value.ToString()
PriceTextBox.Text = row.Cells(5).Value.ToString()
DTP1.Value = row.Cells(6).Value
TxtFee.Text = row.Cells(7).Value.ToString()
TxtVat.Text = row.Cells(8).Value.ToString() '9. column


As 0x01AA has already stated, column index starts with 0 (zero)! So, correct above code accordingly!
For further details, please see:
DataGridView.Columns Property (System.Windows.Forms) | Microsoft Docs[^]
How to: Return a Value from a Procedure - Visual Basic | Microsoft Docs[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900