2

On the line that includes dgdMain.DataSource = dt;, I am getting a "NullReferenceException was unhandled" error. I have tried to find a solution and I'm sure it's simple but I am clearly missing it. Thanks for any input.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Dashboard
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            BindingSource bindingSource = new BindingSource();
            DataTable dt = Program.GetDataTableFromCSV("../../res/sampledata.csv");
            dgdMain.DataSource = dt;

            InitializeComponent();

        }
    }
}

... and here is GetDataTableFromCSV():

public static DataTable GetDataTableFromCSV(string path)
{
    DataTable dataTable = new DataTable();
    String[] values;

    values = File.ReadAllLines(path);

    string[] csvRows = System.IO.File.ReadAllLines(path);
    string[] headers = csvRows[0].Split(',');

    // Adding columns name
    foreach (var item in headers)
        dataTable.Columns.Add(new DataColumn(item));

    string[] fields = null;

    foreach (string csvRow in csvRows)
    {
        //Debug.Write(csvRow+"\r\n");
        fields = csvRow.Split(',');
        DataRow row = dataTable.NewRow();
        row.ItemArray = fields;
        dataTable.Rows.Add(row);
    }

    return dataTable;
}
Gabriel
  • 27
  • 5
  • Why do you create a BindingSource in the constructor that you never use? And why do you execute `File.ReadAllLines(path)` twice in GetDataTable...,(`values` is also never used)? – Tim Schmelter Jun 26 '13 at 22:08
  • 5
    **First** call InitializeComponent() and **then** you can use dgdMain. – Adriano Repetti Jun 26 '13 at 22:08
  • 1
    In addition, CSV files have the potential to have commas inside actual values and thus splitting on the `','` is not the best idea. Refer to http://stackoverflow.com/questions/2081418/parsing-csv-files-in-c-sharp – chancea Jun 26 '13 at 22:10
  • @chancea good point to mention this. – Fabian Bigler Jun 26 '13 at 22:14

2 Answers2

4

InializeComponent must be on top. It should be like this:

    public frmMain()
    {
        InitializeComponent();

        BindingSource bindingSource = new BindingSource();
        DataTable dt = Program.GetDataTableFromCSV("../../res/sampledata.csv");
        dgdMain.DataSource = dt;
    }
Azhar Khorasany
  • 2,712
  • 16
  • 20
2

dgdMain is null and that's why it's throwing a NullReferenceException.

You have to use it after calling InitializeComponent.

Also, have a look at this link. What is a NullReferenceException, and how do I fix it?

Community
  • 1
  • 1
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70