NullReference异常C#

时间:2013-07-14 17:30:49

标签: c# database winforms datatable access-modifiers

我收到以下未处理的异常

  

NullReferenceException未处理。   对象引用未设置为   对象的实例。

等警告

  

字段'Project3_MineSweeper.Form3.form2'永远不会被分配给,并且将始终具有其默认值null

以下是我的DB.cs上的代码

public class DB
    {
    ...

    public DataTable GetData()
        {
            string spName = "GetTime";
            Connection.Open();

            SqlCommand command = new SqlCommand(spName, Connection);
            command.CommandType = CommandType.StoredProcedure;

            SqlDataReader reader = command.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Score");

            while (reader.Read())
            {
                DataRow dr = dt.NewRow();
                dr["name"] = Convert.ToString(reader["name"]);
                dr["timeScore"] = Convert.ToInt32(reader["timeScore"]);
                dt.Rows.Add(dr);
            }

            Connection.Close();
            return dt;
        }
    }

这是Form3.cs的代码

public partial class Form3 : Form
    {
        //THE WARNING
        private Form2 form2; 
        public Form3()
        {
            InitializeComponent();
            loadData();
        }

        public void loadData()
        {
            //UNHANDLED EXCEPTION HERE
            DataTable dt2 = form2.db.GetData(); 
            dgvScore.DataSource = dt2;
        }

    }

最后是Form2.cs

public partial class Form2 : Form
    {
        public DB db;

        private Form3 form3;
        public Form2()
        {
            db = new DB();
            InitializeComponent();
        }
     ...
}

怎么了?我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:2)

你永远不会初始化form2,这会导致在这一行上引起空引用:

  

DataTable dt2 = form2.db.GetData();

您应该执行类似

的操作
  

form2 = new Form2();

取决于您的需要。

 public partial class Form3 : Form
    {
        private Form2 form2; // <--- you never initialize form2
        public Form3()
        {
            InitializeComponent();
            loadData();
        }

        public void loadData()
        {
            //UNHANDLED EXCEPTION HERE
            DataTable dt2 = form2.db.GetData(); 
            dgvScore.DataSource = dt2;
        }

    }

答案 1 :(得分:2)

public void loadData()
{
     form2 = new Form2();  // add this line to init form2 before using
     DataTable dt2 = form2.db.GetData(); 
     dgvScore.DataSource = dt2;
}