Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleEdit data in a FlexGrid control
KeywordsFlexGrid, edit FlexGrid
CategoriesControls
 
When the user double clicks a cell or selects a cell and starts typing, the program calls subroutine GridEdit.
 
Private Sub MSFlexGrid1_DblClick()
    GridEdit Asc(" ")
End Sub

Private Sub MSFlexGrid1_KeyPress(KeyAscii As Integer)
    GridEdit KeyAscii
End Sub
 
GridEdit positions a TextBox over the selected cell and lets the user type into it.
 
Private Sub GridEdit(KeyAscii As Integer)
    ' Position the TextBox over the cell.
    Text1.Left = MSFlexGrid1.CellLeft + MSFlexGrid1.Left
    Text1.Top = MSFlexGrid1.CellTop + MSFlexGrid1.Top
    Text1.Width = MSFlexGrid1.CellWidth
    Text1.Height = MSFlexGrid1.CellHeight
    Text1.Visible = True
    Text1.SetFocus

    Select Case KeyAscii
        Case 0 To Asc(" ")
            Text1.Text = MSFlexGrid1.Text
            Text1.SelStart = Len(Text1.Text)
        Case Else
            Text1.Text = Chr$(KeyAscii)
            Text1.SelStart = 1
    End Select
End Sub
 
It the user presses Escape, the program hides the TextBox and discards the user's changes.

If the user presses Return, the program sets focus to the FlexGrid.

If the user presses up or down arrow, the program sets focus to the FlexGrid and moves to a new row. The program doesn't do anything special with left or right arrows in the TextBox because the TextBox already uses those to let the user move through the text.

 
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As _
    Integer)
    Select Case KeyCode
        Case vbKeyEscape
            ' Leave the text unchanged.
            Text1.Visible = False
            MSFlexGrid1.SetFocus

        Case vbKeyReturn
            ' Finish editing.
            MSFlexGrid1.SetFocus

        Case vbKeyDown
            ' Move down 1 row.
            MSFlexGrid1.SetFocus
            DoEvents
            If MSFlexGrid1.Row < MSFlexGrid1.Rows - 1 Then
                MSFlexGrid1.Row = MSFlexGrid1.Row + 1
            End If

        Case vbKeyUp
            ' Move up 1 row.
            MSFlexGrid1.SetFocus
            DoEvents
            If MSFlexGrid1.Row > MSFlexGrid1.FixedRows Then
                MSFlexGrid1.Row = MSFlexGrid1.Row - 1
            End If

    End Select
End Sub
 
When the FlexGrid gets the focus, the program checks whether the TextBox is visible. If it is, that means the user has just accepted the changes (pressed Return or up/down arrow). The program copies the changes into the FlexGrid and hides the TextBox.
 
Private Sub MSFlexGrid1_GotFocus()
    If Text1.Visible Then
        MSFlexGrid1.Text = Text1.Text
        Text1.Visible = False
    End If
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated