posted by 권오성의 Biomedical Engineering 2007. 9. 20. 10:26
FlexGrid Insert/Remove Example
 
SUMMARY
 
이번에는 FlexGrid에서 특정 위치에 칼럼을 삽입하거나 삭제하는 방법을 배워볼 것이다. 엑셀에서 칼럼을 추가하거나 삭제할 때의 방식과 비슷하도록 하기 위해 고정행 위에서 마우스 오른쪽 버튼을 클릭할 때 팝업 메뉴를 표시한 후 처리하도록 구성했다(아래 그림 참조). 추가가 가능한 칼럼은 과목 칼럼으로 한정한다.
사용자 삽입 이미지


 




BASIS

이 예제를 완성하려면 비주얼 베이직에서 팝업 메뉴를 표시하는 방법과 FlexGrid에서 칼럼을 추가하거나 삭제하는 간단한 방법에 대해 알아야 한다. 당연하게도(^^).... 참고문헌 [1], [2]에서 각 방법에 대한 친절한 설명을 찾을 수 있었다. 아래에 퍼왔으니 참고하시길...
 
 
Pop-Up Menus (참고문헌 [2]에서 가져왔음)

Visual Basic also supports pop-up menus, those context-sensitive menus that most commercial applications show when you right-click on an user interface object. In Visual Basic, you can display a pop-up menu by calling the form's PopupMenu method, typically from within the MouseDown event procedure of the object:
 
Private Sub List1_MouseDown(Button As Integer, Shift As Integer, _
        X As Single, Y As Single)
    If Button And vbRightButton Then
        ' User right-clicked the list box.
        PopupMenu mnuListPopup
    End If
End Sub

The argument you pass to the PopupMenu method is the name of a menu that you have defined using the Menu Editor. This might be either a submenu that you can reach using the regular menu structure or a submenu that's intended to work only as a pop-up menu. In the latter case, you should create it as a top-level menu in the Menu Editor and then set its Visible attribute to False. If your program includes many pop-up menus, you might find it convenient to add one invisible top-level entry and then add all the pop-up menus below it. (In this case, you don't need to make each individual item invisible.) The complete syntax of the PopupMenu method is quite complex:
 
PopupMenu Menu, [Flags], [X], [Y], [DefaultMenu]
 

By default, pop-up menus appear left aligned on the mouse cursor, and even if you use a right-click to invoke the menu you can select a command only with the left button. You can change these defaults using the Flags argument. The following constants control the alignment: 0-vbPopupMenuLeftAlign (default), 4-vbPopupMenuCenterAlign, and 8-vbPopupMenuRightAlign. The following constants determine which buttons are active during menu operations: 0-vbPopupMenuLeftButton (default) and 2-vbPopupMenuRightButton. For example, I always use the latter because I find it natural to select a command with the right button since it's already pressed when the menu appears:
 

PopupMenu mnuListPopup, vbPopupMenuRightButton
 

The x and y arguments, if specified, make the menu appear in a particular position on the form, rather than at mouse coordinates. The last optional argument is the name of the menu that's the default item for the pop-up menu. This item will be displayed in boldface. This argument has only a visual effect; If you want to offer a default menu item, you must write code in the MouseDown event procedure to trap double-clicks with the right button.
 
 
 
ColPosition Property
Moves a given column to a new position.
 
Syntax
[form!]vsFlexGrid.ColPosition(Col As Long)[ = NewPosition As Long ]
 
Remarks
The Col and NewPosition parameters must be valid column indices (in the range 0 to Cols - 1), or an error will be generated.
When a column or row is moved with ColPosition or RowPosition, all formatting information moves
with it, including width, height, alignment, colors, fonts, etc. To move text only, use the Clip property instead.
The ColPosition property gives you programmatic control over the column order. You may also use the ExplorerBar property to allow users to move columns with the mouse.
 
 
IMPLEMENTATION
 
팝업 메뉴를 표시하는 이벤트로 MouseUp을 선택했다. 일단 마우스 오른쪽 버튼을 눌렀는지 확인한 후 다음으로 과목명 칼럼을 클릭했는지 확인한다. 두가지 조건을 모두 만족하면 엑셀의 동작방식과 비슷한 효과를 주기 위해 해당 칼럼을 모두 선택 상태로 만들고 팝업 메뉴를 표시한다.
 
Private Sub FG_MouseUp(Button As Integer, Shift As Integer, _
                       X As Single, Y As Single)
    If Button And vbRightButton Then
        '
과목명 셀을 클릭할 때만 팝업 메뉴를 표시한다.
        If (FG.MouseRow = 1) And (FG.MouseCol > 1) And (FG.MouseCol < FG.Cols - 2) Then
            '
선택한 느낌이 들도록....
            FG.Col = FG.MouseCol
            FG.Row = FG.MouseRow + 1
            FG.RowSel = FG.Rows - 1
            FG.ColSel = FG.MouseCol

            '
팝업 메뉴 표시함.
            PopupMenu mnuGridPopup
        End If
    End If
End Sub
 
 
"Insert Column" 메뉴를 선택하면 과목명을 입력받은 후 칼럼을 추가하고 양식을 유지시키기 위한 몇가지 작업을 추가로 처리한다. 핵심 코드는 굵게 표시한 2줄이다. 칼럼수를 늘린 후에 ColPosition 속성을 이용해서 추가된 칼럼(.Cols-1)을 사용자가 선택한 칼럼(.Col) 앞으로 이동시키는 것이다. 아주 간편하게 처리된다.
 
Private Sub mnuInsertColumn_Click()
    With FG
        ' insert column
        Dim str As String
        str = InputBox("
과목명을 입력하세요")
        If str <> "" Then
            .Cols = .Cols + 1          ' add column
            .ColPosition(.Cols - 1) = .Col    ' move into place

            .Cell(flexcpText, 1, .Col) = str
            .Cell(flexcpAlignment, 1, .Col) = flexAlignCenterCenter
            .Cell(flexcpText, 0, .Col) = "
과목"
        End If
    End With
End Sub
 
사용자 삽입 이미지
 
 
 
"Remove Column" 메뉴를 선택하면 사용자가 선택한 칼럼(.Col)을 마지막 칼럼(.Cols-1)으로 이동시킨 후에 칼럼의 수를 1만큼 감소시켜 삭제하는 효과를 준다. 어려울게 없다.
 
Private Sub mnuRemoveColumn_Click()
    With FG
        ' delete column
        .ColPosition(.Col) = .Cols - 1 ' move to right
        .Cols = .Cols - 1              ' delete column

        '
칼럼이 삭제됐으므로 계산을 다시 수행한다.
        Dim nTotal As Integer
        Dim dAverage As Single

        For i = 2 To .Rows - 1
            nTotal = .Aggregate(flexSTSum, i, 2, i, .Cols - 3)
            dAverage = .Aggregate(flexSTAverage, i, 2, i, .Cols - 3)

            .Cell(flexcpText, i, .Cols - 2) = CStr(nTotal)
            .Cell(flexcpText, i, .Cols - 1) = Format(dAverage, "#,##.0")
        Next
    End With
End Sub
 
 
지금까지 FlexGrid가 제공하는 기능 중 내가 주로 쓸 몇가지 기능 위주로 알아봤다. 매뉴얼을 살펴보니 이것 외에도 다양한 기능을 제공하는데, 그럼에도 불구하고 300달러의 가격 밖에 안되니 가격대 성능비가 뛰어난 제품이라 하겠다. 아주 마음에 든다.
 
 
REFERENCE
 
[1] VSFlexGrid 8.0 Manual, ComponentOne, 2005.
     - f:\ftp_root\program\develop\FlexGrid\VSFlexGrid8Manual2005.pdf
     - pp.269, FAQ: How can I add or delete a column at a given position?
[2] Francesco Balena, "Programming Microsoft Visual Basic 6.0", Microsoft Press, 1999.
     - Chapter 3. Intrinsic Controls, Menus.
 
Project Folder : D:\KDSONG\Study\Visual Basic\Controls\VSFlexGrid\FlexGridInsertRemove\
 
KEYWORDS : FlexGrid grid selection insert remove column copy paste 리드 복사 붙여넣기 선택 영역
열 칼럼 삽입 삭제