Pregunta

I am getting the following unhandled exception

NullReferenceException was unhandled. Object reference not set to an instance of an object.

and something like warning

Field 'Project3_MineSweeper.Form3.form2' is never assigned to, and will always have its default value null

Here is the code on my 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;
        }
    }

And here's the code for 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;
        }

    }

Lastly Form2.cs

public partial class Form2 : Form
    {
        public DB db;

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

What's wrong? And what should I do to fix this problem?

¿Fue útil?

Solución

you never initialize form2, which makes it cause a nullreference on this line:

DataTable dt2 = form2.db.GetData();

You should do something like

form2 = new Form2();

Depending on where you need it.

 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;
        }

    }

Otros consejos

public void loadData()
{
     form2 = new Form2();  // add this line to init form2 before using
     DataTable dt2 = form2.db.GetData(); 
     dgvScore.DataSource = dt2;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top