MsFlexGrid控件没有提供文本直接编辑的功能,一般使用一个TextBox来间接实现对MsFlexGrid当前网格直接编辑的功能:在按下一个键(非回车)后,就把TextBox移动到当前的位置并激活,另外在键入回车时也把TextBox移动到当前的位置并激活,并使文本框内容与当前网格中内容一致,并全部选中,编辑完后在键入回车或移动到其他网格时,就把TextBox中的内容放到当前网格中。
软件步骤
1、打开VB,建立一个新的工程。
2、在菜单“工程”中选择“部件”,在列表中选中“Microsoft FlexGrid Control ”
3、放一个MsFlexGrid控件和一个TextBox控件(Text1)到Form1。修改MsFlexGrid控件的名称为Grid1,设置Grid1的行和列都为6,固定行和列为都为0。设置Text1的 Visiable为False,BorderStyle为None。
4、在Form1的代码中增加声明:
Const ASC_ENTER = 13 'Enter
Dim gRow As Integer
Dim gCol As Integer
5、增加代码到Grid_KeyPress过程:
Private Sub Grid1_KeyPress(KeyAscii As Integer)
' Move the text box to the current grid cell:
Text1.Top = Grid1.CellTop + Grid1.Top
Text1.Left = Grid1.CellLeft + Grid1.Left
' Save the position of the grids Row and Col for later:
gRow = Grid1.Row
gCol = Grid1.Col
' Make text box same size as current grid cell:
Text1.Width = Grid1.CellWidth - 2 * Screen.TwipsPerPixelX
Text1.Height = Grid1.CellHeight - 2 * Screen.TwipsPerPixelY
' Transfer the grid cell text:
Text1.Text = Grid1.Text
' Show the text box:
Text1.Visible = True
Text1.ZOrder 0 ' 把 Text1 放到最前面!
Text1.SetFocus
' Redirect this KeyPress event to the text box:
If KeyAscii <> ASC_ENTER Then
Text1.Text = ""
SendKeys Chr$(KeyAscii)
Else
Text1.SelStart = 0
Text1.SelLength = Len(Text1)
End If
End Sub
6、增加代码到Text1_KeyPress过程:
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = ASC_ENTER Then
Grid1.SetFocus ' Set focus back to grid, see Text_LostFocus.
KeyAscii = 0 ' Ignore this KeyPress.
End If
End Sub
7、增加代码到Text1_LostFocus过程:
Private Sub Text1_LostFocus()
Dim tmpRow As Integer
Dim tmpCol As Integer
' Save current settings of Grid Row and col. This is needed only if
' the focus is set somewhere else in the Grid.
tmpRow = Grid1.Row
tmpCol = Grid1.Col
' Set Row and Col back to what they were before Text1_LostFocus:
Grid1.Row = gRow
Grid1.Col = gCol
Grid1.Text = Text1.Text ' Transfer text back to grid.
Text1.SelStart = 0 ' Return caret to beginning.
Text1.Visible = False ' Disable text box.
' Return row and Col contents:
Grid1.Row = tmpRow
Grid1.Col = tmpCol
End Sub
8、大功告成。按F5或点击运行开始测试。可以实现任意地在Grid 中移动,按回车或其它键可以开始或结束编辑。
附件为VB6源文件:https://static.assets-stash.eet-china.com/album/old-resources/2009/3/17/0079ef43-40c2-4e86-8a71-31c07c2703ad.rarMsFlexGrid_Edit.RAR
用户377235 2012-11-12 16:17
这代码错误