2017-06-08 8 views
-1

IF/ELSE clausesを使用してNULLでセルを "処理"しようとすると、自分のコードが常に例外に入ります。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) 

あなたの価値はあなたがとNullReferenceExceptionを取得しますnullの場合、ここでToString()を呼び出さないでください。単にValue自体をテストしてください。実際に

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

、あなたのケースでは、あなたはnull coalescing operatornull conditional operator??

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

?.にそれを短縮することができます。