VB.Net Array question

Started by
3 comments, last by alexmoura 19 years, 7 months ago
Hi, I'm messing around with a listview in VB.NET and I'm having a problem with declaring an array of ListViewItems. Here is what I have so far:

'Test function for populating information in a listview
Private Sub LoadList(ByVal ListView1 As ListView, ByVal dsRecord As ADODB.Recordset)

        Dim listitem1() As ListViewItem
        Dim ctri As Integer

        ListView1.BeginUpdate()
        ListView1.Clear()
        ListView1.Columns.Insert(0, "String", 100, HorizontalAlignment.Left)
        ListView1.Columns.Add("Test", 100, HorizontalAlignment.Left)
        ListView1.Columns.Add("Test2", 100, HorizontalAlignment.Left)
        ListView1.Columns.Add("Test3", 100, HorizontalAlignment.Left)
        ListView1.Columns.Add("Test4", 100, HorizontalAlignment.Left)

        For ctri = 0 To 9
            listitem1(ctri) = New ListViewItem() 'This line generates the error

            listitem1(ctri).SubItems.Add("subitem" & ctri)
            listitem1(ctri).SubItems.Add("subitem" & ctri)
            listitem1(ctri).SubItems.Add("subitem" & ctri)

            ListView1.Items.Add(listitem1(ctri))
        Next ctri

        ListView1.EndUpdate()

    End Sub


This is the error it generates:

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication6.exe

Additional information: Object reference not set to an instance of an object.


Can anyone here show me the correct way of coding an array of an unknown size and using it to populate my listview? Thanks Ranthalion [edited to reflect changes in code] [Edited by - Ranthalion on September 22, 2004 10:36:18 AM]
Advertisement
Arrays in vb.net are zero based. In your for loop you are starting at 1 instead of zero. Hence element zero is null.
VB.NET arrays are zero based and you are initializing the array starting a 1 instead of zero in the for loop. Hence you are getting a null reference at element 0.
Oh! thanks for pointing that out, I made the change and tried it again, but I still get the same error at the same line...
You've never initialized the array listitem1 - try declaring it as :
Dim listitem1(0) As ListViewItem
or
Dim listitem1() As ListViewItem = new listitem1(0){}

This will create an array with a single element.

This topic is closed to new replies.

Advertisement