VB6.0 MSHFlexGrid控件添加数据三种方法

1.绑定到数据源

  程序代码程序代码
Option Explicit

Dim objConn As ADODB.Connection
Dim objRs As ADODB.Recordset

Private Sub Form_Load()
On Error Resume Next

Set objConn = New ADODB.Connection
Set objRs = New ADODB.Recordset

objConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\demo3.mdb;"
objConn.Open
objRs.CursorLocation = adUseClient
objRs.Open "Select ProductId,ProductName,Discontinued FROM Products", objConn, adOpenStatic, adLockReadOnly
Set MSHFlexGrid1.DataSource = objRs

If Err.Number <> 0 Then
MsgBox Err.Description
End If

On Error GoTo 0
End Sub

'释放资源
Private Sub Form_Unload(Cancel As Integer)

'不操作此步会出错:The current row is not available
If TypeName(MSHFlexGrid1.DataSource) <> "Nothing" Then
Set MSHFlexGrid1.DataSource = Nothing
End If

If TypeName(objRs) <> "Nothing" Then
objRs.Close
Set objRs = Nothing
End If

If TypeName(objConn) <> "Nothing" Then
objConn.Close
Set objConn = Nothing
End If
End Sub

2.使用AddItem方法添加数据

程序代码 程序代码
MSHFlexGrid1.Cols = 5

MSHFlexGrid1.AddItem vbTab & "1" & vbTab & "2" & vbTab & "3" & vbTab & "4"
MSHFlexGrid1.AddItem vbTab & "5" & vbTab & "6" & vbTab & "7" & vbTab & "8"
MSHFlexGrid1.AddItem vbTab & "9" & vbTab & "10" & vbTab & "11" & vbTab & "12"
MSHFlexGrid1.AddItem vbTab & "13" & vbTab & "14" & vbTab & "15" & vbTab & "16"

'删除默认空白行
'此操作不能放在 MSHFlexGrid1.Cols = 5 后,否则出错: Cannot remove last non-fixed row.
MSHFlexGrid1.RemoveItem (1)

3.逐一单元格添加数据

程序代码 程序代码
Dim i, j, k As Integer

'设置行列数
With MSHFlexGrid1
.Rows = 5
.Cols = 5
End With

'添加表头
MSHFlexGrid1.Row = 0
For i = 1 To MSHFlexGrid1.Cols - 1
MSHFlexGrid1.Col = i
MSHFlexGrid1.Text = "列" & i
Next

'添加记录
k = 1
For i = 1 To MSHFlexGrid1.Rows - 1
For j = 1 To MSHFlexGrid1.Cols - 1
MSHFlexGrid1.Row = i
MSHFlexGrid1.Col = j
MSHFlexGrid1.Text = k
k = k + 1
Next
Next

说明:添加部件"Microsoft Hierarchical FlexGrid Control 6.0 (OLEDB)"才能使用MSHFlexGrid。       
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页