在进行数据库编程的时候,经常会用到MSFlexGrid控件进行数据显示。并且对数据进行排序是必不可少的一个环节。使用WINDOWS系统的用户,会习惯于点击标题进行数据排序。而MSFlexGrid控件本身没有这个功能,笔者经过实践,总结出了点击MSFlexGrid标题进行排序的方法,与大家一起分享。
崔占民
EMAIL:CUIZM@163.COM
先添加MSFlexGrid控件,方法:菜单->工程->部件->Microsoft FlexGrid Control 6.0(后面为版本号),代码如下:
Option Explicit
Private Const STR_SORT_ASC = "△"
Private Const STR_SORT_DESC = "▽"
Private Sub Form_Load()
Dim i As Long
'添加一些试验数据
With MSFlexGrid1
.Rows = 51
.Cols = 5
For i = 0 To 50
.TextMatrix(i, 0) = ("Col" & i)
.TextMatrix(i, 1) = ("Col" & i)
.TextMatrix(i, 2) = ("Col" & i)
.TextMatrix(i, 3) = ("Col" & i)
.TextMatrix(i, 4) = ("Col" & i)
Next
End With
End Sub
'排序函数
Public Sub Sort(sgrd As MSFlexGrid, y As Single)
With sgrd
If y >= .RowPos(0) And y < .RowPos(1) Then
If .Tag <> "" Then
If .Tag <> .Col Then
.TextMatrix(0, .Tag) = Left(.TextMatrix(0, .Tag), Len(.TextMatrix(0, .Tag)) - 1)
End If
End If
If Right(.TextMatrix(0, .Col), 1) = STR_SORT_ASC Then
.Sort = flexSortGenericAscending
.TextMatrix(0, .Col) = Replace(.TextMatrix(0, .Col), STR_SORT_ASC, STR_SORT_DESC)
ElseIf Right(.TextMatrix(0, .Col), 1) = STR_SORT_DESC Then
.Sort = flexSortGenericDescending
.TextMatrix(0, .Col) = Replace(.TextMatrix(0, .Col), STR_SORT_DESC, STR_SORT_ASC)
Else
.Sort = flexSortGenericDescending
.TextMatrix(0, .Col) = .TextMatrix(0, .Col) & STR_SORT_ASC
End If
.Tag = .Col
End If
End With
End Sub
Private Sub MSFlexGrid1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
Sort MSFlexGrid1, y
End Sub
代码不多,不过实现的功能还是很方便的~~~~~