0

I am trying to export my DataGredView to Excel File, But i am getting this error as shown in the picture. enter image description here

 private void Buttonexport_Click(object sender, EventArgs e)
    {
        if (dataGridView1.Rows.Count > 0)
        {
            Microsoft.Office.Interop.Excel.Application xcelApp = new Microsoft.Office.Interop.Excel.Application();
            xcelApp.Application.Workbooks.Add(Type.Missing);

            for(int i = 1; i < dataGridView1.Columns.Count + 1 ; i++)
            {
                xcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            for(int i = 0; i < dataGridView1.Rows.Count; i++)
            {

                for(int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    xcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }

            }
            xcelApp.Columns.AutoFit();
            xcelApp.Visible = true;

        }
    }
  • This is a very usual problem. The duplicate explains in great detail your problem. Basically your code access a cell and whatever it finds there it tries to convert it to a string. But if the content is null? calling ToString on a NullReference trigger this exception. So split that line in two, read the value in an object variable and only if it is not null call ToString – Steve Apr 19 '20 at 17:05
  • Thank you so much STEVE, for your explanation, my problem is solved :) – Mahde Al Jamil Apr 19 '20 at 17:42

0 Answers0