2014-02-12 127 views
0

這是我第一次使用ArrayList。我嘗試添加到BarcodeArray作爲ArrayList)和執行與所述錯誤消息失敗:VB.net - 添加到ArrayList

對象引用不設置爲一個對象的一個​​實例。

我的代碼如下所示:當執行線2出現

'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) 

此消息。如何從文本框中將文本添加到ArrayList中而不會出現此錯誤?

+0

BarcodeArray沒什麼。只需初始化它。Dim ar as new ArrayList() –

+1

只是好奇你的理由是需要爲列出的每個不同的值維護一個單獨的ArrayList。從他們的名字來看,它似乎更適合於類似'Product'類的'Barcode','Category'等屬性。然後,您將填充一個List(Of Product)列表,它可以包含所有這些值爲每個產品。 –

回答

2

在.NET中,您需要實例化對象,然後才能調用它們的方法。例如:

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

的解決方案是用的ArrayList來初始化變量:

Dim a As ArrayList 

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

,或者可選地:

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

順便說一句,ArrayList是一個古老的類主要爲了向後兼容而存在。當你開始一個新項目,使用generic List class代替:

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

您需要實例化它纔可以使用。在線2的問題是,它是null在那個時候(NothingVB.NET),因爲不創建

它,因爲你要添加到列表中的值具有同類型這是String我建議你使用的List(Of String)代替ArrayList

嘗試以下操作:

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 
2

這ISS你得到的是你在使用它們之前沒有實例化你的ArrayLists。你需要做這樣的事情讓你的代碼工作:

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

但在你的情況,我想我會創建一個新的類:

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

然後我會用它的代碼像這樣:

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 ... 
}) 

這將讓你使用一個單一的Product對象,而不是單獨的ArrayList對象,這將是一個維護的噩夢。