-1

My code is always entering the exception, does not matter if I try to "treat" the cell with NULL using IF/ELSE clauses.

My catch System.Exception error is: "Object reference not set to an instance of an object"

Situation: If I enter a NULL value on the Datagrid, an error will occur and the rest of the data is not saved.

       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
Fabio Soares
  • 101
  • 2
  • 12

1 Answers1

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

Don't call ToString() here, if your value is null you'll get a NullReferenceException. Simply test Value itself.

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

In fact, in your case you could shorten it to

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

?. being the null conditional operator and ?? being the null coalescing operator.

0xFF
  • 808
  • 1
  • 12
  • 33