Link to home
Start Free TrialLog in
Avatar of enrique_aeo
enrique_aeo

asked on

export to excel from datagrid - object reference not set to an instance of an object - datagrid is null

i have this code
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        '// Disable paging
        GridView1.AllowPaging = False

        '// exluded columns arraylist
        Dim defaultExcludedColumns As New ArrayList()

        '// Always exclude these columns
        defaultExcludedColumns.Add("")

        '// Send to base Excel export method
        ExportGridView(GridView1, "Excel-Name", defaultExcludedColumns)

        '// Rebind with paging enabled
        GridView1.AllowPaging = True
    End Sub

before calling this method ExportGridView need to validate that the GridView1 has at least one row

exportarERRORgridNULL.jpg
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Can you tell me if gridView  or gridView.HeaderRow is not null? (Put a breakpoint in that line and inspect the values)
If so, your problem is that you are overriding the response, thus the gridview lost its contents.
Avatar of enrique_aeo
enrique_aeo

ASKER

THE GRIDVIEW IS NOTHING, VIEW FILE
but I need to validate if the datagrid has data before calling
 ExportGridView (GridView1, "Excel" Name ", defaultExcludedColumns)
gridNULL.jpg
The problem is in your If statement.

When you say (reading from your screenshot):
If grdView.HeaderRow isNot Nothing And GrdView.HeaderRow.Cells IsNot Nothing Then

the program actually checks BOTH statements in the IF clause. But, if HeaderRow is nothing, then HeaderRow.Cells causes the "Object not referenced to an instance of an object).

What you need to do is to use AndAlso, specifically:
If grdView.HeaderRow isNot Nothing AndAlso GrdView.HeaderRow.Cells IsNot Nothing Then

With this syntax, the code will check the first and only if it is true, it will move to the second. So, If HeaderRow is Nothing, it will never check for HeaderRow.Cells and no error will be raised.
I was thinking of something like this
If (gvwQryInscripciones.Rows.Count <> 0) Then
            ExportGridView(gvwQryInscripciones, "Excel-Name", defaultExcludedColumns)
End If
you think?
ASKER CERTIFIED SOLUTION
Avatar of klakkas
klakkas

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
it is OK