0

I am trying to sort a gridview in code. It was working, and now I am getting a

Object reference not set to an instance of an object

error. It is happening on the line where I assign the gridview's datasource to a datatable. Here is the section of code (note, the gridivew works and pages just fine)

Protected Sub gvBasicList_Sorting(sender As Object, e As GridViewSortEventArgs)
    Dim gv As GridView = DirectCast(sender, GridView)
    Dim dv As DataView = TryCast(gv.DataSource, DataView) <ERROR HERE
    Dim dataTable As DataTable = dv.Table
    Dim sortdir As [String] = ""
    If e.SortExpression <> "" And e.SortExpression IsNot Nothing Then
        If gvSortExpression = e.SortExpression Then
            gvSortDirection = GetSortDirection()
        Else
            gvSortDirection = "ASC"
        End If
        gvSortExpression = e.SortExpression
        gvBasicList.EditIndex = -1
    End If
    Session("listsort") = e.SortExpression
    Session("listsortdirection") = gvSortDirection
    gv.DataSource = GetSortedData(dataTable, e.SortExpression, gvSortDirection)
    gv.DataBind()
End Sub
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Dana J
  • 15
  • 3
  • debug and see what your function GetSortedData(dataTable, e.SortExpression, gvSortDirection) is returning – Karthik Ganesan May 20 '14 at 20:47
  • Karthik, it is erroring before getsorteddata fires. – Dana J May 20 '14 at 20:52
  • All NullReferenceExceptions are the same. You're trying to do something to an object that is null. Run the debugger, see what's null, then take steps to make sure it's not null before you try to use it. – mason May 20 '14 at 20:52
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 20 '14 at 20:55
  • John saunders, since I found an answer, and it had NOTHING to do with that link you posted, so your making this as a duplicate is false. Stupid Stackoverflow. – Dana J Mar 22 '17 at 17:47

1 Answers1

0

After a postback your GridView's datasource needs to be bound to the grid again in order for this to work.

Here is some sample code I use that maybe will prove helpful to you:

Protected Sub gridInboxApps_Sorting(sender As Object, e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gridInboxApps.Sorting

    'must make sure the data is bound before trying to sort, otherwise the grid will contain a null datasource
    BindGridInbox()

    Dim dv As New DataView(gridInboxApps.DataSource)
    dv.Sort = e.SortExpression 'sort direction is attached to grid field

    gridInboxApps.DataSource = dv
    gridInboxApps.DataBind()

    dv.Dispose()

End Sub
Taylor Brown
  • 1,689
  • 2
  • 17
  • 33