Reputation: 26
Here is the definition of the structure
Structure Ct
Public name As String
Structure Pt
Public identity As String
End Structure
Public Pty() As Pt
End Structure
Public Cty() As Main.Ct
This is declared in a module called main.
Then this piece of code, located in a subroutine in another class is run
Dim i As Integer = 1
For Each item As String In cataList.Items
'cataList is a listbox
Cty(i).name = item
i += 1
Next
It throws a nullReferenceException.
What is missing? I need the structure to be global.
Upvotes: 0
Views: 110
Reputation: 38905
Your array is declared but not instanced as the linked dupe describes. But an array of structures is not the most efficient way to do what you are trying.
Friend Class Ct ' cries out for a meaningful name
Public Property Name As String
Private _identities As New List(of String) ' ie "Pty"
' a ctor to create with the name prop
Public Sub New(n As String)
Name = n
End Sub
Public Sub AddIdentity(id As String)
_identities.Add(id)
End Sub
' get one
Public Function GetIdentity(index As Integer) As String
Return _identities(index)
End Sub
' get all
Public Function Identities As String()
Return _identities.ToArray
End If
' and so on for Count, Clear...
End Class
Then a list of these things:
' as (elegantly) described in the NRE link, NEW creates an instance:
Friend Cty As New List(Of Ct)
Then fill the List from the ListBox:
For Each s As String In cataList.Items
Cty.Add(New CT(s)) ' create CT with name and add to list
Next
The more you work with Lists and Collections, the more you will appreciate how much more flexible and powerful they are. For instance, there might not be a need to manually populate the ListBox
at all. Use the DataSource
property to bind the list to the listbox; this is more efficient because you map rather than copy the data to the UI control:
' tell the listbox which property on your class (Type) to display
cataList.DisplayMember = "Name"
cataList.DataSource = Cty
For cases where you want/need to copy the data:
For n As Integer = 0 to Cty.Count-1
cataList.Items.Add(Cty(n).Name)
Next
Or:
For Each item As Ct In cty
cataList.Items.Add(item.Name)
Next
Upvotes: 1
Reputation: 15813
cataList.Items is made up of listviewitems instead of strings. That may be causing problems. In addition, Cty has no members when it is declared.
Try this:
ReDim Cty(cataList.Items.Count-1)
For Each item As ListViewItem In cataList.Items
'cataList is a listbox
Cty(i).name = item.Text
i += 1
Next
You could also use a list (with .add) instead of an array to avoid the redim.
Upvotes: 1