MSFlexGrid强制整行实现表头排序(双向)

发表于:2007-05-25来源:作者:点击数: 标签:MSFlexGrid强制整行表头实现
'******************************************** ' MSF lexGrid在强制整行选择的情况下实现表头排序 ' '功能:在单击表头时根据当前列进行排序,再次单 '击反序排列。单击数据区域时进行整行选择 ' '2005-09-21 FieldMAX '*********************************
'********************************************
'MSFlexGrid在强制整行选择的情况下实现表头排序
'
'功能:在单击表头时根据当前列进行排序,再次单
'      击反序排列。单击数据区域时进行整行选择
'
'2005-09-21 FieldMAX
'********************************************

Private Sub Form_Load()
'创建一个8*8的MSFlexGrid并在其中填入随机数
Dim i As Long
Dim j As Long
MSFlexGrid1.Rows = 8
MSFlexGrid1.Cols = 8
MSFlexGrid1.FormatString = "|A|B|C|D|E|F|G"
For i = 0 To 7
    MSFlexGrid1.ColWidth(i) = 615
Next
For i = 1 To 7
    MSFlexGrid1.TextMatrix(i, 0) = i
    For j = 1 To 7
        MSFlexGrid1.TextMatrix(i, j) = Int(Rnd * 1000)
        n = n + 1
    Next
Next
End Sub

Private Sub MSFlexGrid1_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
'在MSFlexGrid的实际应用中经常需要强制整行选并且还需要排序功能,
'但是由于MSFlexGrid本身的缺陷,在正常情况下是无法实现两者兼得的。
'唯一的变通方法就是使用MouseDown或MouseUp事件独有的"X","Y"坐标来
'确定点击的列,再进行排序。
'这个排序程序已经经过修改,可以实现升序和降序两种排序同时存在。
    Dim i As Long
    Dim j As Long
    Dim Cw As Long
    '如果Y坐标点击的是表头区域
    If y < MSFlexGrid1.RowHeight(0) Then
        Cw = 0
    '用循环语句判断X在那一列,I代表列数
        For i = 0 To MSFlexGrid1.Cols - 1
            Cw = Cw + MSFlexGrid1.ColWidth(i)
            If x < Cw Then Exit For
        Next
        If i < MSFlexGrid1.Cols Then
        '↑
            If Left(MSFlexGrid1.TextMatrix(0, i), 1) <> "↓" Then
                For j = 0 To 7
                    If Left(MSFlexGrid1.TextMatrix(0, j), 1) = "↓" Or Left(MSFlexGrid1.TextMatrix(0, j), 1) = "↑" Then MSFlexGrid1.TextMatrix(0, j) = Mid(MSFlexGrid1.TextMatrix(0, j), 2)
                Next
                MSFlexGrid1.Col = i   '定位列坐标
                MSFlexGrid1.Sort = 1    '进行升序排列
                MSFlexGrid1.TextMatrix(0, i) = "↓" & MSFlexGrid1.TextMatrix(0, i)
            Else
                For j = 0 To 7
                    If Left(MSFlexGrid1.TextMatrix(0, j), 1) = "↓" Or Left(MSFlexGrid1.TextMatrix(0, j), 1) = "↑" Then MSFlexGrid1.TextMatrix(0, j) = Mid(MSFlexGrid1.TextMatrix(0, j), 2)
                Next
                MSFlexGrid1.Col = i   '定位列坐标
                MSFlexGrid1.Sort = 2    '进行升序排列
                MSFlexGrid1.TextMatrix(0, i) = "↑" & MSFlexGrid1.TextMatrix(0, i)
            End If
        End If
    End If
End Sub

原文转自:http://www.ltesting.net