我想通過包含DBNull值的列對DataGridView控件進行排序。此DataGridView控件綁定到SQL Server 2012數據庫。如何對包含DBNull值的DataGridView控件中的列進行排序? VB.NET
當我單擊headercell(按升序排序)時,DBNull值會先於其餘整數值排序,以便列中的頂部行全部爲空,然後在整數值之後1,2,3等按升序排列。
我該如何解決這個問題?我寧願DataGridView控件對頂部的值進行排序,然後是DBNulls。
我試圖插入一個較高的值到空白單元格中,然後將它們正確排序,但是當我將這些值返回到System.DBNull.value時,排序順序恢復爲上述方式。
我的代碼如下:
If dgv.Columns(e.ColumnIndex).Name.EndsWith("Position") Then
intSortingRunningPosition = 1000
dgv.Sort(baseColumn, System.ComponentModel.ListSortDirection.Ascending)
newColumn.HeaderCell.SortGlyphDirection = Windows.Forms.SortOrder.Ascending
For Each dr As DataGridViewRow In dgv.Rows
If dr.Cells(e.ColumnIndex).Value Is System.DBNull.Value Then
dr.Cells(e.ColumnIndex).Value = intSortingRunningPosition
intSortingRunningPosition += 1
End If
Next
dgv.Sort(newColumn, System.ComponentModel.ListSortDirection.Ascending)
For Each dr As DataGridViewRow In dgv.Rows
If dr.Cells(e.ColumnIndex).Value >= 1000 Then
dr.Cells(e.ColumnIndex).Value = System.DBNull.Value
End If
Next
End If
很抱歉,如果這是令人困惑的。謝謝!
更新:
我已經修改我的代碼用的IComparer的方法來工作,並紛紛拿出如下:
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
Dim DataGridViewRow1 As DataGridViewRow = CType(x, DataGridViewRow)
Dim DataGridViewRow2 As DataGridViewRow = CType(y, DataGridViewRow)
Dim CompareResult As Integer
Dim intDGV1Cell0Value As Integer = Nothing
Dim intDGV1Cell1Value As Integer = Nothing
Dim intDGV2Cell0Value As Integer = Nothing
Dim intDGV2Cell1Value As Integer = Nothing
Try
intDGV1Cell0Value = CInt(DataGridViewRow1.Cells(0).Value)
Catch ex As Exception
intDGV1Cell0Value = Int32.MaxValue
End Try
Try
intDGV1Cell1Value = CInt(DataGridViewRow1.Cells(1).Value)
Catch ex As Exception
intDGV1Cell1Value = Int32.MaxValue
End Try
Try
intDGV2Cell0Value = CInt(DataGridViewRow2.Cells(0).Value)
Catch ex As Exception
intDGV2Cell0Value = Int32.MaxValue
End Try
Try
intDGV2Cell1Value = CInt(DataGridViewRow2.Cells(1).Value)
Catch ex As Exception
intDGV2Cell1Value = Int32.MaxValue
End Try
' Try to sort based on the Last Name column.
CompareResult = System.String.Compare(intDGV1Cell1Value, intDGV2Cell1Value)
' If the Last Names are equal, sort based on the First Name.
If CompareResult = 0 Then
CompareResult = System.String.Compare(intDGV1Cell0Value, intDGV2Cell0Value)
End If
Return CompareResult * sortOrderModifier
End Function
空值現在不排序的。關於我在這裏做錯的任何想法?我相信,我身體有點走,因爲它是天方夜譚......
您可以使用自定義分揀機,在這裏看一個MSDN的例子:http://msdn.microsoft.com/en-us/library/ms171608.aspx –
我認爲,路線會導致我相同問題,我現在有。我已經使用了自定義的排序器,但DBNull值似乎計爲0或小於1,因此它們按升序(DBNull,DBNull,1,2,3)在列表頂部排序,列表底部按降序排列(3,2,1,DBNull,DBNull)。 – J2Tuner
如果對客戶端進行排序(而不是SQL查詢),則可以同時使用SortCompare事件或自定義IComparer實現。只要將DBNull作爲特殊情況處理(如果lhs是DBNull,則返回Int32.MinValue,如果rhs是DBNull,則返回Int32.MaxValue)。看看這個排序方法的例子。 –