日期:2010-07-14  浏览次数:20495 次

开始在网上查找到asp的无限分类,但是asp.net的几乎找不到,找到的也是跟TreeView结合起来的.
找到asp版本的代码有几种,原来都差不多是采用递归算法.
其中表结构都是如下:
表名称是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() +