此代码在下面的指定行抛出ArgumentNullException,我不知道为什么。
Private Sub ShaftLoad()
Dim newShaft As New Shaft
Dim shaftlist As New List(Of Shaft)
shaftlist = DBShaft.GetShaftList
Dim shaftArray(shaftlist.Count) As String
For i As Integer = 0 To shaftlist.Count - 1
shaftArray(i) = (shaftlist(i).ShaftName)
Next
ShaftComboBox.Items.AddRange(shaftArray) 'Exception is thrown here.
End Sub
答案 0 :(得分:1)
Dim shaftArray(shaftlist.Count) As String
这是VB.NET的一个怪癖,一个数组声明声明数组中的最后一个有效索引,而不是数组中元素的数量。因此,您的数组是一个太大的元素。这将在AddRange()调用中弹出,它会添加一个Nothing的字符串。修正:
Dim shaftArray(shaftlist.Count - 1) As String
或完全使用Linq绕过显式数组:
Dim shaftlist = DBShaft.GetShaftList()
ShaftComboBox.Items.AddRange(shaftList.Cast(Of Object).ToArray())
答案 1 :(得分:0)
根据MSDN
ArgumentNullException - items参数中的项目为null。
也许你可以做这样的事情......
For i As Integer = 0 To shaftlist.Count - 1
shaftArray(i) = Iif(shaftlist(i).ShaftName=Nothing, String.Empty, shaftlist(i).ShaftName)
Next
答案 2 :(得分:0)
shaftArray(shaftList.Count)
为空。您的数组是0索引的,最大索引为shaftlist.Count
。但你永远不会设置最大元素。你可能想要:
Dim shaftArray(shaftlist.Count - 1) As String