在包含的行上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;
}