树型控件如何连接数据库?并且显示字段名?
'新建工程,在FORM1上
'添加2个文本框text 一个命名为dbpath,一个命名为KEY
'添加一个Combo 命名为ziduan
'添加一个Treeview 命名为tableview
'添加一个MSHFlexGrid 命名为msh
'添加2个安钮 '一个命名为open ,一个命名为SEARCH
'*********************************代码贴在这里,看不明白加我QQ87904619*******************************
'*********************************时间紧,可能会有BUG。你自己看下吧**********************************
Dim conn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim tablenm As String '存储表名使用
Private Sub open_Click()
Dim strconn As String
Dim i As Integer
i = 0
cmd1.Filter = "Access数据库文件|*.mdb|All Files|*.*"
cmd1.DialogTitle = "选择数据库文件"
cmd1.ShowOpen
'打开数据库文件
If cmd1.FileName <> "" Then
dbpath.Text = cmd1.FileName
strconn = "provider=microsoft.jet.oledb.4.0;data source=" & cmd1.FileName
'打开数据源连接
If conn.State = adStateOpen Then
conn.Close
End If
conn.open strconn
'读取所有表名称,填充到TreeView
tabletree.Nodes.Clear
Dim nd1 As Node
Set nd1 = tabletree.Nodes.Add(, , "pt", "数据库文件")
Set rs = conn.OpenSchema(adSchemaTables)
Do Until rs.EOF
'判断是否是表
If rs!TABLE_TYPE = "TABLE" Then
Dim nd As Node
'将表名添加到TreeView
Set nd = tabletree.Nodes.Add("pt", tvwChild, "pt" & i)
nd.Text = rs!TABLE_NAME
i = i + 1
End If
rs.MoveNext
Loop
rs.Close
End If
End Sub
'取表里所有字段的函数
Private Function getTable(ByVal nodename As String) As Recordset
Dim str As String
str = "select * from " & nodename
Set rs = New ADODB.Recordset
rs.open str, conn, 3, 3
Set getTable = rs
End Function
'查找函数
Private Function getKey() As Recordset
Dim str As String
str = "select * from " & tablenm & " where " & Trim(ziduan.Text) & " like '%" & key.Text & "%'"
rs.open str, conn, 3, 3
Set getKey = rs
End Function
Private Sub search_Click()
Set msh.DataSource = getKey
rs.Close
End Sub
'点击表名时使用的函数
Private Sub tabletree_NodeClick(ByVal Node As MSComctlLib.Node)
Dim i As Integer
If Node.key <> "pt" Then
tablenm = Trim(Node.Text)
Set rs = getTable(Trim(Node.Text))
ziduan.Clear
For i = 0 To rs.Fields.Count - 1
ziduan.AddItem rs(i).Name
Next i
rs.Close
End If
End Sub
'本程序在win2000下读取VB目录NOTHWIND数据库通过