2017-06-08 101 views
-1

我的代碼總是進入異常,如果我嘗試「治療」與NULL使用IF/ELSE clauses細胞無所謂。異常上的DataGridView(NullReferenceException異常) - C#

我捕捉System.Exception的錯誤是: "Object reference not set to an instance of an object"

情況: 如果我輸入的數據網格中的NULL值,就會發生錯誤和其他數據不保存。

 private void ExportToExcel() 
    { 
     // Creating a Excel object. 
     Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application(); 
     Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing); 
     Microsoft.Office.Interop.Excel._Worksheet worksheet = null; 

     try 
     { 

      worksheet = workbook.ActiveSheet; 

      worksheet.Name = "ExportedFromDatGrid"; 

      int cellRowIndex = 1; 
      int cellColumnIndex = 1; 


      //Loop through each row and read value from each column. 
      for (int i = -1; i < dataGridView1.Rows.Count - 1; i++) 
      { 
       for (int j = 0; j < dataGridView1.Columns.Count; j++) 
       { 
        // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. 
        if (cellRowIndex == 1) 
        { 
         worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText; 
        } 
        else 
        { 

         if (dataGridView1.Rows[i].Cells[j].Value.ToString() != null) 
         { 
          worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString(); 
         } 
         else 
         { 
          worksheet.Cells[cellRowIndex, cellColumnIndex] = String.Empty; 
         } 


         // working: 
         //worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString(); 
        } 
        cellColumnIndex++; 
       } 
       cellColumnIndex = 1; 
       cellRowIndex++; 
      } 

      //Getting the location and file name of the excel to save from user. 
      SaveFileDialog saveDialog = new SaveFileDialog(); 
      saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"; 
      saveDialog.FilterIndex = 2; 

      if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       workbook.SaveAs(saveDialog.FileName); 
       MessageBox.Show("Export Successful"); 
      } 
     } 
     catch (System.Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     finally 
     { 
      excel.Quit(); 
      workbook = null; 
      excel = null; 
     } 

    } // end ExportToExcel 

回答

0
if (dataGridView1.Rows[i].Cells[j].Value.ToString() != null) 

不要叫ToString()在這裏,如果你的值爲空,你會得到一個NullReferenceException。簡單地測試Value本身。

if (dataGridView1.Rows[i].Cells[j].Value != null) 

事實上,在你的情況,你可以縮短到

worksheet.Cells[cellRowIndex, cellColumnIndex]=dataGridView1.Rows[i].Cells[j].Value?.ToString() ?? ""; 

?.作爲null conditional operator??作爲null coalescing operator