我正在尝试在代码中对gridview进行排序。它正在工作,现在我得到了一个
对象引用未设置为对象的实例
错误。它发生在我将gridview的数据源分配给数据表的行上。这是代码部分(注意,gridivew工作和页面很好)
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
答案 0 :(得分:0)
回发后,GridView的数据源需要再次绑定到网格上才能生效。
以下是我使用的一些示例代码,可能会对您有所帮助:
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