.net 无限级分类

using  System;
using  System.Data;
using  System.Configuration;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;
using  System.Text;
using  System.Data.SqlClient;

public   partial   class  _Default : System.Web.UI.Page 
{

    System.Text.StringBuilder sb 
=   new  StringBuilder();
    
// 默认深度1;
     public   int  i  =   1 ;

    
protected   void  Page_Load( object  sender, EventArgs e)
    {
        
if ( ! this .IsPostBack)
        {
            
this .buildTree();
        }
    }

    
///   <summary>
    
///  创建树
    
///   </summary>
     private   void  buildTree()
    {

        DataSet ds 
=  ExecuteDataSet( " select * from Sort " );

        
// 建立关系
        ds.Relations.Add( " SortRelation " , ds.Tables[ 0 ].Columns[ " SortId " ], ds.Tables[ 0 ].Columns[ " ParentSortId " ]);

        
// 遍历每行并根据数据行关系生成树
         foreach  (DataRow dbRow  in  ds.Tables[ 0 ].Rows)
        {
            
if  (dbRow.IsNull( " ParentSortId " ))
            {
                
string  s  =  CreateNode(dbRow[ " SortName " ].ToString());
                sb.Append(s);
                PopulateSubTree(dbRow,i);
                
            }
        }
        
        
this .Response.Write(sb);
    }

   
///   <summary>
   
///  遍历子类
   
///   </summary>
   
///   <param name="dbRow"> 遍历的Row </param>
   
///   <param name="depth"> 深度(用于显示空格个数) </param>
     private   void  PopulateSubTree(DataRow dbRow, int  depth)
    {
        
++ depth;
        
foreach  (DataRow childRow  in  dbRow.GetChildRows( " SortRelation " ))
        {
            
string  s  =   "" ;
            
for  ( int  j = 1 ;j <= depth;j ++  )
            {
                s 
=   " &nbsp "   +  s;
            }
            s 
+=   " |- "   +  childRow[ " SortName " ].ToString()  +   " <br> " ;
           sb.Append(s);
           PopulateSubTree(childRow,depth);
        }
    }

    
///   <summary>
    
///  显示父类名称
    
///   </summary>
    
///   <param name="sortname"> 类别名称 </param>
    
///   <returns></returns>
     private   string  CreateNode( string  sortname)
    {
        
string  s  =   " |- " + sortname + " <br> " ;

        
return  s;
     }

     
#region   返回dataset对象
     
///   <summary>
     
///  返回dataset对象
     
///   </summary>
     
///   <param name="sql"> sql语句 </param>
     
///   <returns></returns>
      public  DataSet ExecuteDataSet( string  sql)
     {
         SqlConnection con 
=   new  SqlConnection( " server=.;database=sort;uid=sa;pwd=; " );
         DataSet ds 
=   new  DataSet();
         SqlDataAdapter sda 
=   new  SqlDataAdapter(sql, con);
         sda.Fill(ds);
         
return  ds;
     }
     
#endregion

}

你可能感兴趣的:(.net)