簡體   English   中英

將DataTable分配給DataGridView時,“未處理NullReferenceException”

[英]“NullReferenceException was unhandled” when Assigning DataTable to DataGridView

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

InializeComponent必須在最上面。 應該是這樣的:

    public frmMain()
    {
        InitializeComponent();

        BindingSource bindingSource = new BindingSource();
        DataTable dt = Program.GetDataTableFromCSV("../../res/sampledata.csv");
        dgdMain.DataSource = dt;
    }

dgdMain為null ,這就是為什么它拋出NullReferenceException的原因。

您必須在調用InitializeComponent之后使用它。

另外,請查看此鏈接。 什么是NullReferenceException,如何解決?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM