我做了一个3层的应用程序,我想在表中插入数据,它向我显示一个错误...它显示了一个空异常

时间:2012-07-27 15:24:38

标签: c# c#-4.0 c#-to-vb.net

数据库层...................

public static void AddEnrollment(StudentScore enrollment)
{
       SqlConnection conn = MyDB.GetConnection();

       string insertStm = "insert into EnrollmentTable (StudentID,CourseID,DateEnrolled,Score) values (@StudentID,@CourseID,@DateEnrolled,@Score)";

       SqlCommand insertComm = new SqlCommand(insertStm, conn);

       insertComm.Parameters.AddWithValue("@StudentID", enrollment.EnrollmentData.StudentData.StudentID);
       insertComm.Parameters.AddWithValue("@CourseID", enrollment.EnrollmentData.CourseData.CourseID);
       insertComm.Parameters.AddWithValue("@DateEnrolled", enrollment.EnrollmentData.DOE);
       insertComm.Parameters.AddWithValue("@Score", enrollment.Score);

       try
       {
           conn.Open();
           insertComm.ExecuteNonQuery();
       }
       catch (SqlException sqlex)
       {
           throw sqlex;
       }
       finally
       {
           conn.Close();
       }

业务层...............

public class StudentScore
{
    public Enrollment EnrollmentData { get; set; }
    public int Score { get; set; }

    public StudentScore()
    {
    }

    public StudentScore(Enrollment aEnrollmentData, int aScore)
    {
        EnrollmentData = aEnrollmentData;
        Score = aScore;
    }
}

表示层..................

private void button5_Click(object sender, EventArgs e)
{
        StudentScore enrollment = new StudentScore();

        enrollment.EnrollmentData.StudentData.StudentID = comboBox1.SelectedValue.ToString();
        enrollment.EnrollmentData.CourseData.CourseID = comboBox2.SelectedValue.ToString();
        enrollment.EnrollmentData.DOE = DateTime.Now;

        EnrollmentDB.AddEnrollment(enrollment);

        MessageBox.Show("Student is enrolled this course.");
    }   

它告诉我这个错误

  

异常:enrollment.EnrollmentData.StudentData.StudentID =   comboBox1.SelectedValue.ToString();

请帮我解决这个问题?

1 个答案:

答案 0 :(得分:1)

enrollment.EnrollmentData尚未初始化。如果没有进一步的细节,请更改

StudentScore enrollment = new StudentScore();

StudentScore enrollment = new StudentScore(new Enrollment(), 0);