介绍 我有一个问题在我的电子邮件,“如何使用ADO来填充数据的树状视图和列表视图*。mdb文件?我试着用以下几句话来回答这个问题:我希望我能成功。这篇文章展示了如何: 连接数据库填充TreeView与表的名称和字段namePopulate ListView与记录的选择表 背景 演示项目有一种形式。我添加以下控件到我的表单(frmDataView): 两个标签(lblDatabase)显示文件名和(lblTableName)显示表名两个按钮,一个(cmdLoadData)连接数据库文件,另一个(cmdClose)结束showImageList (ImageList1)加载一些iconsTreeView (tvData)和ListView (lvData)。 使用Code 隐藏,收缩,复制Code
' Here is the code to get Tables name from the database file: Dim cn As ADODB.Connection Dim rst As ADODB.Recordset Dim MyDataFile As String Dim strCon As String Dim tabName As String Dim dbNode As Node Dim tabNode As Node ' Don't use: On Error goto label, but use following: On Error Resume Next 'set root node of TreeView. Set dbNode = tvData.Nodes.Add(, , "RootDB", "Database", "DatabaseClose") dbNode.Tag = "RootDB" MyDataFile = App.Path & "DataFile" & "test.mdb" strCon = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & MyDataFile & ";" Set cn = New ADODB.Connection cn.CursorLocation = adUseClient cn.Open strCon Set rst = cn.OpenSchema(adSchemaTables) rst.MoveFirst Do Until rst.EOF If rst("TABLE_TYPE").Value = "VIEW" Or rst("TABLE_TYPE").Value = "TABLE" Then tabName = rst("TABLE_NAME").Value Set tabNode = tvData.Nodes.Add("RootDB", tvwChild, "X" & tabName, _ tabName, "TableClose") tabNode.Tag = "Tables" End If rst.MoveNext Loop rst.Close ' Here is the code to get Fields name from all Tables: Dim rs As ADODB.Recordset Dim fldName As String Dim n As Integer Dim c As Integer Dim i As Integer Dim j As Integer Set rs = New ADODB.Recordset c = tvData.Nodes("RootDB").Children ' first table n = tvData.Nodes("RootDB").Child.FirstSibling.Index For i = n To c + n tabName = tvData.Nodes(i).Text ' get field name Set rs = cn.Execute("SELECT * FROM [" & tabName & "]", 1, 1) For j = 0 To rs.Fields.Count - 1 fldName = rs.Fields(j).Name Set fldNameNode = tvData.Nodes.Add("X" & tabName, tvwChild, _ "X" & fldName, fldName, "imgField") fldNameNode.Tag = "Fields" Next j rs.Close Next i
你可以在表格(frmDataView)中阅读完整的代码: InitListView子:初始化ListViewLoadListView子:加载ListView datacmdLoadData_Click子:联系数据库filetvData_Collapse子:改变icontvData_Expand子:改变icontvData_NodeClick子:看到如何填充ListView TreeView记录当单击表名称,你也可以看到我们如何更改图标ColumnHeader ListView 当点击TreeView的字段名 讲话 当你创建一个新的项目,你必须添加ListView, TreeView和imagels&ist控件到工具箱从组件对话框:Microsoft Windows通用控件6.0你必须添加引用:“Microsoft ActiveX数据对象2.x”。 最后一句话 我希望这篇文章是有用的,并帮助您显示表,字段和记录从数据库文件到TreeView和ListView。如果你有任何想法或发现任何问题,请告诉我。感谢CodeProject和所有人。 Mostafa KaisounM_Kaisoun@hotmail.com 历史 2009年10月18日:初任 本文转载于:http://www.diyabc.com/frontweb/news2313.html