VB在列表框中显示来自多维数组的元素

时间:2014-01-20 01:05:21

标签: arrays vb.net multidimensional-array listbox

由于某些奇怪的原因,当我使用循环显示数组的元素时,我收到错误。我似乎无法理解我在做什么或做得不对。到目前为止这是代码。这不适合上课,我正在学习自己。

Option Strict On
Option Explicit On
Option Infer Off

Public Class Form1

Private strExams(49, 2) As String
Dim count As Integer = 0

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

    Dim strStudent As String = txtStudent.Text
    Dim strTest As String = txtTest.Text
    Dim strScore As String = txtScore.Text

    If count <= 49 Then
        strExams(count, 0) = strStudent
        strExams(count, 1) = strTest
        strExams(count, 2) = strScore
        count += 1
    End If

    txtStudent.Text = String.Empty
    txtTest.Text = String.Empty
    txtScore.Text = String.Empty

    txtStudent.Focus()

End Sub

Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click

    Dim intHighRow As Integer = strExams.GetUpperBound(0)
    Dim intHighCol As Integer = strExams.GetUpperBound(1)
    Dim intR As Integer
    Dim intC As Integer
    Do While intC <= intHighCol
        intR = 0
        Do While intR <= intHighRow
            lstMessage.Items.Add(strExams(intR, intC))
            intR += 1
        Loop
        intC += 1
    Loop

End Sub

这是我点击显示按钮时出现的错误。

System.Windows.Forms.dll中出现未处理的“System.ArgumentNullException”类型异常

附加信息:值不能为空。

1 个答案:

答案 0 :(得分:1)

试试这个。这对我来说更有意义。您收到空错误的原因是您没有填充数组中的所有内容,并且列表框无法列出空项。因此,解决方法是仅枚举已经具有值的项目,因此,只循环直到最后一次计数值。

Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
    Dim intR As Integer

    lstMessage.Items.Clear()
    Do While intR < count
        lstMessage.Items.Add(strExams(intR, 0) & " - " & strExams(intR, 1) & " - " & strExams(intR, 2))
        intR += 1
    Loop
End Sub