ArgumentNullException在vb.net中未处理

时间:2014-09-01 10:57:20

标签: vb.net

调试以下代码时显示ArgumentNullException was Unhandled
请通过简报进行纠正

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim myArry(6) As String
    myArry(0) = "You Can Win"
    myArry(1) = "Jaz"
    myArry(2) = "The Mong he sold his ferrari"
    myArry(3) = "Babu"
    myArry(4) = "The Alchemist"
    myArry(5) = "MT"

    For i As Integer = 0 To myArry.GetUpperBound(0)
        ListBoxBooks.Items.Add(myArry(i))

    Next
End Sub
End Class

2 个答案:

答案 0 :(得分:1)

问题是你初始化了一个包含7个项目但只有6个被初始化的数组。因此,最后一个是null / Nothing,它会在ListBoxBooks.Items.Add中引发异常。

因此,您必须仅循环前6个,初始化全部或使用Dim myArry(5) As String来获得包含6个字符串的String()。您还可以检查它是否为空,即使这似乎毫无意义:

但是,我也会使用Length代替GetUpperBound

Dim myArry(5) As String
myArry(0) = "You Can Win"
myArry(1) = "Jaz"
myArry(2) = "The Mong he sold his ferrari"
myArry(3) = "Babu"
myArry(4) = "The Alchemist"
myArry(5) = "MT"

现在,以下If myArry(i) IsNot Nothing - 检查是多余的,无论如何我都会显示:

For i As Integer = 0 To myArry.Length - 1
    If myArry(i) IsNot Nothing Then
        ListBoxBooks.Items.Add(myArry(i))
    End If
Next

注意:您还必须使用myArry.Length - 1,否则如果您尝试访问不可用的索引(数组基于零),则会导致下一个异常。

答案 1 :(得分:0)

    For Each item As String In myArry
      If item<>"" Then
       ListBoxBooks.Items.Add(item)
      End IF
    Next