What causes the error? (Error: Object reference not set to an instance of object.)

BenTam 1,781 Reputation points
2023-07-01T14:05:39.4533333+00:00

Dear All,

Could you point out what causes the error "object reference not set to an instance of object"?

private void FillSlotsDo(int i, string TheDate)
{
	string sSqlCourse = "Select CONVERT(NVARCHAR, cl.date, 120) As TheDate, cs.CourseID, cs.SubjectID, " + 	"cs.DurationIn5Min, cs.Remark, tn.engname"
                " From Course cs" +
                " Left Join " +
                " Trainer tn On cs.TrainerID = tn.TrainerID" +
                " Right Join CourseLesson cl On cl.CourseID = cs.CourseID" +
                " Where cl.date = " + TheDate + " And btime between '" + cutOffTimes[i] + "' and '" + cutOffTimes[i + 1] + "'" +
                " Order By cl.date, cl.btime";

            OleDbDataAdapter dataadapter = new OleDbDataAdapter(sSqlCourse, myConnection);
            DataSet[] ds = new DataSet[3];
            ds[i+1] = ds[i].Copy();
	        dataadapter.Fill(ds[i], "Course_table");
            ds[i].Tables[0].DefaultView.RowFilter = "TheDate.ToString ";
            int rowCount = ds[i].Tables[0].Rows.Count;
            string CurrDate = ds[i].Tables["Course_table"].Rows[0]["CurrDate"].ToString();
            string CourseID = ds[i].Tables["Course_table"].Rows[0]["CourseID"].ToString();
            string SubjectID = ds[i].Tables["Course_table"].Rows[0]["SubjectID"].ToString();
            string DurationIn5Min = ds[i].Tables["Course_table"].Rows[0]["DurationIn5Min"].ToString();
            string remark = ds[i].Tables["Course_table"].Rows[0]["Remark"].ToString();
            string trainerID = ds[i].Tables["Course_table"].Rows[0]["Trainer"].ToString();
} 
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-07-03T02:41:35.8433333+00:00

    Hi @BenTam-3003 ,Welcome to Microsoft Q&A, Updated:

    You can't use ds[i] = new DataSet() like this.

    You can first use private DataSet[] dataSets = new DataSet[3];

    Then initialize when needed.

    I wrote you a simple example, you can refer to it.

    using System;
    using System.Data;
    using System.Data.OleDb;
    using System.Windows.Forms;
    namespace _7_20_1
    {
        public partial class Form1: Form
        {
            DateTime dateTimeFrom = new DateTime(2023, 7, 20, 00, 00, 00);
            int[] Ids = new int[3]
            {
                1, 2, 3
            };
            static readonly string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=xxxxxx.mdb;Persist Security Info=False;";
            private DataSet[] dataSets = new DataSet[3];
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                dateTimePicker1.Value = dateTimeFrom;
                FillSlots();
                dataGridView1.DataSource = dataSets[0].Tables["Course_table"];
                dataGridView2.DataSource = dataSets[1].Tables["Course_table"];;
                dataGridView3.DataSource = dataSets[2].Tables["Course_table"];;
            }
            private void FillSlots()
            {
                for(int i = 0; i < 3; i++)
                {
                    FillSlotsDo(i);
                }
            }
            private void FillSlotsDo(int i)
            {
                string sSqlCourse = "SELECT * FROM tmpTable WHERE [Id] = " + Ids[i];
                using(OleDbConnection connection = new OleDbConnection(connectionString))
                {
                    try
                    {
                        connection.Open();
                        OleDbDataAdapter dataadapter = new OleDbDataAdapter(sSqlCourse, connection);
                        dataSets[i] = new DataSet(); // Initialize the DataSet before filling it
                        dataadapter.Fill(dataSets[i], "Course_table");
                        // ... Rest of the code ...
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }
    }
    

    enter image description here

    enter image description here


    User's image

    From the screenshot of the error, it is obvious that The line DataSet[] ds = new DataSet[3]; creates an array of DataSet objects. However, the elements in the array are not initialized, so when you attempt to access ds[i] and ds[i+1], they will throw an exception. You need to initialize these elements with valid DataSet objects before accessing them.

    DataSet[] ds = new DataSet[3];
    ds[i] = new DataSet(); // Initialize the DataSet object
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.