ASP.NET非TreeView的无限分类示例(zhuan)
采用递归算法.
其中表结构都是如下:
表名称是ClassName
id 主键
sid 对应的父类的id
ClassName 对应类别的名称.
代码段一:
1function loadNextType(upid,rank)
2 dim rs
3 set rs="select * from classname where sid="&upid
4 do while not rs.eof
5 loadNextType=loadNextType &rs("ClassName")&"<br>"& string("-",rank) & loadNextType(rs("id"),rank+1)
6 rs.movenext
7 loop
8end function调用时:response.write(loadNextType(0,0))
另外一段代码就跟上面原理就一样的.只不过是加入了树型结构的显示方式.
代码段二:
1'定义第一级分类
2sub mainfl()
3 dim rs
4 set rs=conn.execute("select id,F_id,F_name from ClassNae where sid=0 order by id desc")
5 if not rs.eof then
6 do while not rs.eof
7 response.write rs(2) & "<br>"
8 call subfl(rs(0)," |-") '循环子级分类
9 rs.movenext
10 if rs.eof then exit do '防上造成死循环
11 loop
12 end if
13end sub
14'定义子级分类
15sub subfl(fid,strdis)
16 dim rs1
17 set rs1=conn.execute("select id,sid,ClassName from ClassName where sid="&fid&" order by id desc")
18 if not rs1.eof then
19 do while not rs1.eof
20 response.write rs1(2) & "<br>"
21 call subfl(rs1(0)," "&strdis) '递归子级分类
22 rs1.movenext
23 if rs1.eof then
24 rs1.close
25 exit sub
26 end if
27 loop
28 end if
29end sub
我参考上面的代码改成了asp.net版本的无限分类.开始遇到了语法上的限制.当时的处理是直接把rs换成SqlDataReader,然后加以修改,代码如下(错误代码):
测试数据库的表Tree结构是:id,ParentID,Name。
1private void Display(string parentid/**//*, int rank*/)
2 {
3 SqlDataReader dr;
4 SqlCommand cmd;
5 String strSQL;
6
7 strSQL = "Select * From Tree Where ParentID =" + parentid + "Order By ID DESC";
8 cmd = new SqlCommand(strSQL,conn);
9 //cmd.Connection.Open();
10
11 using(dr = cmd.ExecuteReader())
12 {
13 while(dr.Read())
14 {
15 Response.Write(dr["Name"].ToString() + "<br>");
16 Display(dr["ID"].ToString());
17 }
18 }
19 cmd.Connection.Close();
20 }调用使用Display("0").
错误原因是SqlDataReader每次使用之后都需要关闭,所以DataReader是不可以嵌套使用的.
后来我改成了用DataTable的形式实现了无限分类,但是感觉这种方式的效率不高,需要改进(还在研究中)
修改后的代码如下:
1private void Display(string parentid, String space)
2 {
3 DataTable dt;
4 String strSQL;
5 strSQL = "Select * From Tree Where ParentID =" + parentid + " Order By ID DESC";
6
7 SqlDataAdapter sda = new SqlDataAdapter(strSQL, conn);
8 DataSet ds = new DataSet();
9 sda.Fill(ds, "Tree");
10 dt = ds.Tables["Tree"];
11
12 if (dt.Rows.Count > 0)
13 {
14 foreach (DataRow dr in dt.Rows)
15 {
16 strOpinion += space + "<font color=red>[" + dr["Name"].ToString() +"<br>";
17 Display(dr["ID"].ToString(), " " + space, false);
18 }
19 }
20 }调用时候使用Display("0","↓→→")。
ASP.NET技术网站 http://www.singletowm.com/
posted on 2009-01-20 11:34 linxiao1314 阅读(489) 评论(0) 编辑 收藏 举报