2

在包含的行上dgdMain.DataSource = dt;,我收到“NullReferenceException 未处理”错误。我试图找到一个解决方案,我确信它很简单,但我显然错过了它。感谢您的任何意见。

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();

        }
    }
}

...这里是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;
}
4

2 回答 2

4

InializeComponent 必须在顶部。它应该是这样的:

    public frmMain()
    {
        InitializeComponent();

        BindingSource bindingSource = new BindingSource();
        DataTable dt = Program.GetDataTableFromCSV("../../res/sampledata.csv");
        dgdMain.DataSource = dt;
    }
于 2013-06-26T22:09:44.280 回答
2

dgdMain 为空,这就是它抛出NullReferenceException.

您必须在调用后使用它InitializeComponent

另外,看看这个链接。 什么是 NullReferenceException,我该如何解决?

于 2013-06-26T22:08:45.080 回答