2013-11-14 3 views
0

Итак, я работаю над проектом для класса, который не могу понять ошибку в моем коде. Я просмотрел его, пока не стал синим. Любая помощь в понимании очень ценится. Я пытаюсь загрузить значения в массив, и этот массив печатает значения в списке во второй форме.Почему мои элементы массива элементов списка не отображаются?

Private Sub displayStd_Click(sender As Object, e As EventArgs) Handles displayStd.Click 

    Dim fmtStr As String = "{0,-10}{1,10}{2,15}{3,20}{4,25}" 
    Dim form As New Form2() 
    form.displayLB.Items.Clear() 
    form.displayLB.Items.Add("There are " & Student.Count & " accounts.") 
    form.displayLB.Items.Add(String.Format(fmtStr, "ID", "Name", "Score1", "Score2", "Average Score")) 


    For Each studentObj As Student In students 
     form.displayLB.Items.Add(String.Format(fmtStr, studentObj.ID, 
     studentObj.Name, studentObj.Score1, studentObj.Score2, studentObj.CalculateAverage(studentObj.Score1, studentObj.Score2))) 
    Next 
    form.Show() 
    Me.Hide() 
End Sub 

Я получаю:

An unhandled exception of type 'System.NullReferenceException' occurred in Student Record.exe Additional information: Object reference not set to an instance of an object.

выделяя это как ошибку:

form.displayLB.Items.Add(String.Format(fmtStr, studentObj.ID, 
      studentObj.Name, studentObj.Score1, studentObj.Score2, studentObj.CalculateAverage(studentObj.Score1, studentObj.Score2))) 

CalculateAvg метод:

Public Function CalculateAverage(score1 As Integer, score2 As Integer) 

     Dim sum As Double 
     Dim avg As Double 


     sum = score1 + score2 
     avg = sum/2 

     Return avg 


    End Function 

класс Student:

Public Class Student 

    Private IDVALUE As String 
    Private nameValue As String 
    Private score1Value As Integer 
    Private score2Value As Integer 
    Private Shared studentCount As Integer 

    Public Sub New(ByVal id As String, ByVal name As String, ByVal score1 As Integer, ByVal score2 As Integer) 

     IDVALUE = id 
     nameValue = name 
     score1Value = score1 
     score2Value = score2 
    End Sub 

    Public Property ID As String 


     Get 
      Return IDVALUE 
     End Get 
     Set(value As String) 
      IDVALUE = value 
     End Set 
    End Property 

    Public Property Name As String 


     Get 
      Return nameValue 
     End Get 
     Set(value As String) 
      nameValue = value 
     End Set 
    End Property 

    Public Property Score1 As Integer 


     Get 
      Return score1Value 
     End Get 
     Set(value As Integer) 
      score1Value = value 
     End Set 
    End Property 

    Public Property Score2 As Integer 


     Get 
      Return score2Value 
     End Get 
     Set(value As Integer) 
      score2Value = value 
     End Set 
    End Property 

    Public Shared Property Count() As Integer 

     Get 
      Return studentCount 
     End Get 
     Set(ByVal value As Integer) 
      studentCount = value 
     End Set 
    End Property 

    Public Function CalculateAverage(score1 As Integer, score2 As Integer) 

     Dim sum As Double 
     Dim avg As Double 


     sum = score1 + score2 
     avg = sum/2 

     Return avg 


    End Function 

End Class 

Form1 Класс:

Public Class Form1 
    Dim students As Student() 

    Private Sub addStd_Click(sender As Object, e As EventArgs) Handles addStd.Click 
     Dim thisStudent As New Student(idTB.Text, nameTB.Text, CInt(score1TB.Text), CInt(score2TB.Text)) 

     ReDim Preserve students(Student.Count + 1) 
     students(Student.Count + 1) = thisStudent 

     idTB.Text = "" 
     nameTB.Text = "" 
     score1TB.Text = "" 
     score2TB.Text = "" 
    End Sub 
Private Sub displayStd_Click(sender As Object, e As EventArgs) Handles displayStd.Click 

     Dim fmtStr As String = "{0,-10}{1,10}{2,15}{3,20}{4,25}" 
     Dim form As New Form2() 
     form.displayLB.Items.Clear() 
     form.displayLB.Items.Add("There are " & Student.Count & " accounts.") 
     form.displayLB.Items.Add(String.Format(fmtStr, "ID", "Name", "Score1", "Score2", "Average Score")) 


     For Each studentObj As Student In students 
      form.displayLB.Items.Add(String.Format(fmtStr, studentObj.ID, 
      studentObj.Name, studentObj.Score1, studentObj.Score2, studentObj.CalculateAverage(studentObj.Score1, studentObj.Score2))) 
     Next 
     form.Show() 
     Me.Hide() 
    End Sub 
End Class 
+0

Вы проверили метод 'CalculateAverage()' в классе 'Student'? Или вы могли бы показать этот метод и здесь? – Edper

+0

Если вы посмотрите на свой код, где вы загружаете коллекцию 'students', вы найдете ее, но вам нужно будет показать нам, или мы не можем помочь. Либо коллекция 'students' не объявляется как' New', а объекты 'student' не объявляются с помощью' New'. – OneFineDay

+0

Где/как вы объявляете коллекцию? Как вы его заполняете? – OneFineDay

ответ

1

Я думаю, вам нужно использовать List(of T) вместо массива, как это:

Изменить это:

Dim students As Student() 

To:

Dim students As New List(Of Student) 

И это одна:

Private Sub addStd_Click(sender As Object, e As EventArgs) Handles addStd.Click 
    Dim thisStudent As New Student(idTB.Text, nameTB.Text, CInt(score1TB.Text), CInt(score2TB.Text)) 

    ReDim Preserve students(Student.Count + 1) 
    students(Student.Count + 1) = thisStudent 

    idTB.Text = "" 
    nameTB.Text = "" 
    score1TB.Text = "" 
    score2TB.Text = "" 
End Sub 

Для этого один:

Private Sub addStd_Click(sender As Object, e As EventArgs) Handles addStd.Click 
    Dim thisStudent As New Student(idTB.Text, nameTB.Text, CInt(score1TB.Text), CInt(score2TB.Text)) 

    students.Add(thisStudent) 

    idTB.Text = "" 
    nameTB.Text = "" 
    score1TB.Text = "" 
    score2TB.Text = "" 
End Sub 

Теперь, если вы хотите использовать массив, то я думаю, что вам нужно overload ваш New «ING, как:

Public Sub New() 

End Sub 

Затем вы можете создать экземпляр следующим образом:

Dim students As New Student() 

Поскольку вы не смогли создать экземпляр в своем случае без необходимости вводить значения параметров вашего New(ByVal id As String, ByVal name As String, ByVal score1 As Integer, ByVal score2 As Integer).

+0

Извините инструкции, что он должен быть массивом. – SkyVar

+0

Проверьте мой обновленный ответ @SkyVar – Edper

1

Вы не инициализировали массив Student.

Dim students As Student() 

Должно быть;

Dim students() As Student = New Student() {} 'empty array 

ReDim part;

ReDim Preserve students(Student.Count) 
students(Student.Count - 1) = thisStudent 
+0

спасибо, что помогли мне исправить это, но это не решает мою ошибку, которую я все еще получаю. – SkyVar

+0

обновлено ........ – OneFineDay

Смежные вопросы