TreeView控件在编制程序过程中用得比较多。正确的掌握和使用这个控件,可以很好的表示层次关系的数据。在数据库应用系统中,我们可以用TreeView来显示树形结构,如显示目录树、显示班级信息等等,有着很重要的作用
看看下面一个实际的问题:每个年度都有许多的班级,将这些数据层次表示
数据库:access
表:Test
字段:bh(班级编号,文本,主键),nj(年级,文本)
功能:以层次关系表现出数据
测试数据:
bh |
nj |
41020 |
2001 |
41021 |
2001 |
41025 |
2003 |
41026 |
2003 |
41027 |
2003 |
41028 |
2003 |
|
|
添加TreeView控件,2个按钮
2个按钮分别用了两种方法显示数据。但是第二种方法明显优于第一种。
可以仔细的看代码
'引用microsoft activex data object 2.x library
Dim nddata As Node
Dim cnn As ADODB.Connection
Dim rs1 As New ADODB.Recordset
Dim rs2 As New ADODB.Recordset
Private Sub Command1_Click()
On Error Resume Next
Set nddata = TreeView1.Nodes.Add(, , "db", "班级信息")
nddata.Expanded = True
Dim intcount As Integer
Dim inttable As Integer
Dim intfield As Integer
Dim intfn As Integer
rs1.Open "select nj from test group by nj", cnn, 1, 3
inttable = rs1.RecordCount
Do While inttable <> intcount
Set nddata = TreeView1.Nodes.Add("db", tvwChild, "F" & rs1.Fields("nj"), rs1.Fields("nj"))
rs2.Open "select bh,nj from test where nj='" & rs1.Fields("nj") & "'", cnn, 1, 3
intfield = rs2.RecordCount
If intfield <> 0 Then
intfn = 0
Do While intfield <> intfn
Set nddata = TreeView1.Nodes.Add("F" & rs1.Fields("nj"), tvwChild, "S" & rs2.Fields("bh"), rs2.Fields("bh"))
rs2.MoveNext
intfn = intfn + 1
Loop
End If
rs2.Close
rs1.MoveNext
intcount = intcount + 1
Loop
rs1.Close
End Sub
‘第二种方法
Private Sub Command2_Click()
On Error Resume Next
Set nddata = TreeView1.Nodes.Add(, , "db", "班级信息")
nddata.Expanded = True
rs1.Open "select * from test", cnn, 1, 3
Do While Not rs1.EOF
If ca <> rs1.Fields("nj") Then
Set nddata = TreeView1.Nodes.Add("db", tvwChild, "F" & rs1.Fields("nj"), rs1.Fields("nj"))
ca = rs1.Fields("bb")
End If
Set nddata = TreeView1.Nodes.Add("F" & rs1.Fields("nj"), tvwChild, "S" & rs1.Fields("bh"), rs1.Fields("bh"))
rs1.MoveNext
Loop
rs1.Close
End Sub
Private Sub Form_Load()
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\csdn_vb\database\treeview的节点添加\1\test.mdb"
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set con = Nothing
End Sub
本文地址:http://com.8s8s.com/it/it44193.htm