2014-03-06 72 views
1

我不確定要在代碼中更改哪些內容以使列表框顯示每輛車。我想讓我的車輛結構在列表框中顯示

Public Class Form1 

Structure Vehicle 
    Dim Make As String 
    Dim Model As String 
    Dim Doors As Integer 
    Dim Hp As Integer 
    Dim VIN As String 
End Structure 




Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click 
    Dim Vehicles(9) As Vehicle 

    Vehicles(0).Make = "Chevrolet" 
    Vehicles(1).Make = "Dodge" 
    Vehicles(2).Make = "Nissan" 
    Vehicles(3).Make = "Mitsubishi" 

做了一個for循環來顯示每個做

For i = 0 To 4 Step 1 
     ls.Items.Add(Vehicles(i).Make.ToString) 

    Next 


End Sub 
+0

首先,你不需要在'String'上調用'ToString'。除此之外,這不起作用? – David

+1

沒有.tostring我得到「值不能爲空。」 – user3268184

+1

與tostring我得到「對象引用未設置爲對象的實例。」 – user3268184

回答

1

你只有4個實例(0-3)提供的數據:

Vehicles(0).Make = "Chevrolet" 
Vehicles(1).Make = "Dodge" 
Vehicles(2).Make = "Nissan" 
Vehicles(3).Make = "Mitsubishi" 

但是你要從5個實例(0-4)檢索數據:

For i = 0 To 4 Step 1 

String默認爲Nothing,除非您爲其分配一個值。所以你的第五個實例是一個空的實例Vehicle。因此...

這將失敗,因爲Vehicles(4).MakeNothing,你不能調用Nothing的方法(ToString):

ls.Items.Add(Vehicles(i).Make.ToString) 

,這將失敗,因爲Vehicles(4).MakeNothing,你可以」 T時的空或空字符串添加到列表框:

ls.Items.Add(Vehicles(i).Make) 

您需要:

  • 調整你的循環只覆蓋你的數據(For i = 0 To 3 Step 1),或
  • 添加另一個數據元素(Vehicles(4).Make = "Something"),或
  • 添加空檢查你的代碼(If Vehicles(i).Make Is Not Nothing
0

爲什麼你不是嘗試使用Class而不是Structure,並使用list而不是array。由於看起來你自己也沒有多長時間的數據,所以在這種情況下list對你來說是一個不錯的選擇,你可以把它看作是一個在c/C++中的動態數組。以下是我的方式來詮釋

Public Class Form1 

Class Vehicle 
    Dim Make As String 
    Dim Model As String 
    Dim Doors As Integer 
    Dim Hp As Integer 
    Dim VIN As String 

Public Sub New(Dim s As String) 
    Me.Model=s 
End Sub 
End Class 




Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click 
Dim Vehicles As New List(Of Vehicle) 

Vehicles.Add(New Vehicle("Chevrolet")) 
Vehicles.Add(New Vehicle("Dodge")) 
Vehicles.Add(New Vehicle("Nissan")) 
Vehicles.Add(New Vehicle("Mitsubishi")) 

當你循環了,

Dim car as Vehicle 
For each car in Vehicles 
    ls.Items.Add(car.Make) 
Next 

希望它能幫助。

相關問題