NullReferenceException was Unhandled
Everytime I run this code I get a message saying "NullReferenceException was Unhandled". I'm stuck and need help with solving this problem.
Here is my code:
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As New Excel.Worksheet
Dim oRng As Excel.Range
Dim i As Integer
Dim j As Integer
' Start Excel and get Application object.
xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
' Get a new workbook.
xlWorkBook = xlApp.Workbooks.Add
xlWorkSheet = xlWorkBook.ActiveSheet
' Add table headers going cell by cell.
xlWorkSheet.Cells(1, 1).Value = "MANDT"
xlWorkSheet.Cells(1, 2).Value = "BALEID"
xlWorkSheet.Cells(1, 3).Value = "STATUS"
xlWorkSheet.Cells(1, 4).Value = "CREEL1"
xlWorkSheet.Cells(1, 5).Value = "CREEL2"
xlWorkSheet.Cells(1, 6).Value = "CREEL3"
xlWorkSheet.Cells(1, 7).Value = "CREEL4"
xlWorkSheet.Cells(1, 8).Value = "CREEL5"
xlWorkSheet.Cells(1, 9).Value = "CREEL6"
xlWorkSheet.Cells(1, 10).Value = "CREEL7"
xlWorkSheet.Cells(1, 11).Value = "CREEL8"
xlWorkSheet.Cells(1, 12).Value = "ZPACKAGE"
xlWorkSheet.Cells(1, 13).Value = "LOT"
xlWorkSheet.Cells(1, 14).Value = "DISPOSITION"
xlWorkSheet.Cells(1, 15).Value = "PROD_DATE"
xlWorkSheet.Cells(1, 16).Value = "ZRELEASE"
xlWorkSheet.Cells(1, 17).Value = "MATNR"
xlWorkSheet.Cells(1, 18).Value = "WERKS"
xlWorkSheet.Cells(1, 19).Value = "NETWR"
xlWorkSheet.Cells(1, 20).Value = "GROWR"
xlWorkSheet.Cells(1, 21).Value = "zFILE_NAME"
xlWorkSheet.Cells(1, 22).Value = "STATUSP"
xlWorkSheet.Cells(1, 23).Value = "EBELN"
xlWorkSheet.Cells(1, 24).Value = "EBELP"
' Format A1:X1 as bold, vertical alignment = center.
With xlWorkSheet.Range("A1", "X1")
.Font.Bold = True
.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
End With
For i = 0 To DataGridResults.RowCount - 1
For j = 0 To DataGridResults.ColumnCount - 1
xlWorkSheet.Cells(i + 2, j + 1) = _
DataGridResults(j, i).Value.ToString()
Next
Next
' AutoFit columns A:X.
oRng = xlWorkSheet.Range("A1", "X1")
oRng.EntireColumn.AutoFit()
' Make sure Excel is visible and give the user control
' of Excel's lifetime.
xlApp.Visible = True
xlApp.UserControl = True
' Make sure that you release object references.
oRng = Nothing
xlWorkSheet = Nothing
xlWorkBook = Nothing
xlApp.Quit()
xlApp = Nothing
Exit Sub
Err_Handler:
MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
End Sub
here is where I receive the NullReference message:
xlWorkSheet.Cells(i + 2, j + 1) = _
DataGridResults(j, i).Value.ToString()