尝试加载excel时,C#datatable为null

时间:2018-01-15 08:57:33

标签: c#

我正在使用ExcelDataReader扩展将excel文件导入C#datagridview。我可以打开文件并获取它的表格,但每当我尝试点击表格时,我的程序就会中断并说它的数据表为空。请帮我。

我不确定是否是造成问题的var,或者我没有将excel数据更新到数据表中

  namespace Dashboard {
    public partial class Import_Excel : Form {
      public Import_Excel() {
        InitializeComponent();
      }
      DataSet result;

      private void btnLoad_Click(object sender, EventArgs e) {
        using (OpenFileDialog ofd = new OpenFileDialog()) {
          if (ofd.ShowDialog() == DialogResult.OK) {
            using (var stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)) {
              using (var reader = ExcelReaderFactory.CreateReader(stream)) {
                var result = reader.AsDataSet(new ExcelDataSetConfiguration() {
                  UseColumnDataType = true,
                  ConfigureDataTable = (data) => new ExcelDataTableConfiguration() {
                    UseHeaderRow = true
                  }
                });
                cboSheet.Items.Clear();
                DataTableCollection table = result.Tables;

                foreach (DataTable dt in result.Tables) {
                  cboSheet.Items.Add(dt.TableName);
                }
                reader.Close();
              }
            }
          }
        }
      }

      private void cboSheet_SelectedIndexChanged(object sender, EventArgs e) {
        dataGridView1.DataSource = result.Tables[cboSheet.SelectedIndex];
      }

      private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
      }
    }
  }

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

如果方法cboSheet_SelectedIndexChangedbtnLoad_Click()之前发生,则result将为空,因此result.Tables会抛出NullReferenceException

private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
{
  if(result != null) {
    dataGridView1.DataSource = result.Tables[cboSheet.SelectedIndex];
  }
}

或者只使用:dataGridView1.DataSource = result?.Tables[cboSheet.SelectedIndex];(将其设置为null)