简体   繁体   中英

VB.net - Adding to an ArrayList

This is my first time using ArrayList . I have tried to add to BarcodeArray ( as an arraylist ) and execution is failing with the error message:

Object reference not set to an instance of an object.

My code is shown below:

'Populate the arrays        
BarcodeArray.Add(txt_Barcode.Text)
CategoryArray.Add(cmb_Categories.Text)
TitleArray.Add(txt_Title.Text)
DescriptionArray.Add(txt_Description.Text)
QuantityArray.Add(txt_Quantity.Text)
RRPArray.Add(txt_RRP.Text)
CostArray.Add(txt_Cost.Text)

This message appears when line 2 is executed. How do I add text to an ArrayList from a textbox without getting this error?

In .NET, you need to instantiate objects before you can call methods on them. Example:

Dim a As ArrayList
a.Add(...)           ' Error: object reference `a` has not been set

The solution is to initialize the variable with a new ArrayList:

Dim a As ArrayList

a = New ArrayList()
a.Add(...)           

or, alternatively:

Dim a As New ArrayList()
a.Add(...)           

BTW, ArrayList is an old class that mainly exists for backwards compatibility. When you are starting a new project, use the generic List class instead:

Dim a As New List(Of String)()
a.Add(...)           

This issue you're having is that you are not instantiating your ArrayLists before using them. You would need to do something like this to get your code to work:

Dim barcodeArray as New ArrayList()
barcodeArray.Add(txt_Barcode.Text)
... etc ...

But in your case, I think I would create a new class:

Public Class Product
    Public Property Barcode as String
    Public Property Category as String
    Public Property Title as String
    ... etc ...
End Class

Then I would use it in code like this:

Dim productList as New List(Of Product)()
productList.Add(new Product() With {
    .Barcode = txt_Barcode.Text,
    .Category = cmb_Categories.Text,
    .Title = txt_Title.Text,
    ... etc ...
})

This would let you use a single Product object rather than separate ArrayList objects, which would be a maintenance nightmare.

You need to instantiate it before you can use. The problem in line 2 is that it is null at that time ( Nothing in VB.NET ) since it is not created

Since all the values you want to add to the list has same type which is String i suggest you use a List(Of String) instead of ArrayList

Try the following:

Dim BarcodeArray as List(Of String) = New List(Of String)( { txt_Barcode.Text } )
Dim CategoryArray as List(Of String) = New List(Of String)( { cmb_Categories.Text } )
' ...
' Same for the other Lists you will need to use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM