LeCarloVC LeCarloVC - 1 day ago 4
Vb.net Question

Add Range Object reference not set to instance, listview problems

I'm getting this error "Object reference not set to an instance of an object" at this line every time

lstGraph.Items.AddRange(New ListViewItem() {B1, B2, B3, B4, B5, B6})


I have B1 - B6 set as public variables because i have them in IF statements. The context of this program is that each of the B1 - B6 is to hold an amount of * per certain amount of value in another variable, which is where i get in the IF's statement. Each of the B1-B6 variables have their own column in the listview. Here is the code:

Public B1, B2, B3, B4, B5, B6 As New ListViewItem 'Set as public variables in load event


If C1 > 0 Then 'If only the C variables are higher than 0
Dim B1 As New ListViewItem("*", 0) 'Creates an initial item
For C1 = 1 To C1
B1.SubItems.Add("*")
Next
End If
If C2 > 0 Then
Dim B2 As New ListViewItem("*", 0)
For C2 = 1 To C2
B2.SubItems.Add("*")
Next
End If
If C3 > 0 Then
Dim B3 As New ListViewItem("*", 0)
For C3 = 1 To C3
B3.SubItems.Add("*")
Next
End If
If C4 > 0 Then
Dim B4 As New ListViewItem("*", 0)
For C4 = 1 To C4
B4.SubItems.Add("*")
Next
End If
If C5 > 0 Then
Dim B5 As New ListViewItem("*", 0)
For C5 = 1 To C5
B5.SubItems.Add("*")
Next
End If
If C6 > 0 Then
Dim B6 As New ListViewItem("*", 0)
For C6 = 1 To C6
B6.SubItems.Add("*")
Next

End If
'This is where i'm getting the error
lstGraph.Items.AddRange(New ListViewItem() {B1, B2, B3, B4, B5, B6})


I have the listview created on the form and I've set the columns in the load event but i don't know why i get this object reference not set to an instance of an object error.

Update: After doing some research it only happens when i have the variables set with nothing, this is a slight problem because at various times any one of these variables is going to have no value. Also on another problem, nothing is being added to the listview. I've tried to the best of my knowledge to have the variables B1-B6 to display in their corresponding column IF only any of the variables have an item and subitem. I can get something to work but not the way i intend it.

Answer

You need all elements correctly valued before executing:

lstGraph.Items.AddRange(New ListViewItem() {B1, B2, B3, B4, B5, B6})

So if in your code you have something like:

C1 = 1, C2 = 2, C3 = 3, C4 = 4, C5 = 5, C6 = 6

your AddRange will work but if anyone of the "C?" variables is < 1 then the code will fail because "B?" will not be valued.

You need to add an Else statement to give a value to B? even if C? is < 1

something like:

If C2 > 0 Then
    Dim B2 As New ListViewItem("*", 0)
    For C2 = 1 To C2
        B2.SubItems.Add("*")
    Next
Else
    B2.SubItems.Add("")
End If

EDIT If you don't see anything it may be caused by:

Dim B2 As New ListViewItem("*", 0)

When you use Dim B2 you create another variable with the same name of the Public B2 already declared

Try using

B2 = New ListViewItem("*", 0)
Comments