对数据进行递归排序以树状显示

源数据:
id  上级id
1    0
2    0
11   1
21   1
111  11

树状后显示:
1
--11
---111
2
--21

ExpandedBlockStart.gif代码

#region  自定义方法

    
#region  bind TypeID
    
private   void  fn_Bind_ddl_Type()
    {
        DataSet ds;

        BLL.MyTypeInfo bll_Type 
=   new  BLL.MyTypeInfo();
        ds 
=  bll_Type.SelectAllTypeForChoose();

        
this .ddl_Type.Items.Clear();
        
if  (ds  !=   null   &&  ds.Tables.Count  >   0   &&  ds.Tables[ 0 ].Rows.Count  >   0 )
        {
            DataTable dtPara 
=  ds.Tables[ 0 ];
            DataTable dtTree 
=   new  DataTable();
            dtTree 
=  dtPara.Clone();
            fn_ChangeToTree(
ref  dtTree, dtPara,  0 " 0 " ); // 从顶级开始递归遍历

            
this .ddl_Type.DataSource  =  dtTree;
            
this .ddl_Type.DataTextField  =  dtTree.Columns[ 1 ].ToString();
            
this .ddl_Type.DataValueField  =  dtTree.Columns[ 0 ].ToString();
            
this .ddl_Type.DataBind();
        }
        
this .ddl_Type.Items.Insert( 0 new  ListItem( "" " 0 " ));
    }
    
#endregion

    
#region  将信息 整理成树状
    
private   void  fn_ChangeToTree( ref  DataTable dtTree, DataTable dtPara,  int  intLevel,  string  strParentTypeID)
    {
        intLevel
++ ;
        
string  strLeftPre  =   "" ;
        
if  (intLevel  >   1 )
        {
            strLeftPre 
=   " | "   +  strLeftPre.PadLeft(intLevel  *   2 ' - ' );
        }
        DataTable dt1 
=   new  DataTable(); // 当前级别
        dt1  =  dtPara.Clone();
        DataTable dt2 
=   new  DataTable(); // 下一级
        dt2  =  dtPara.Clone();

        
for  ( int  i  =   0 ; i  <  dtPara.Rows.Count; i ++ )
        {
            DataRow dr 
=  dtPara.Rows[i];
            
string  strRowParentType  =  dr[ " ParentType " ].ToString();
            
if  (strRowParentType  ==  strParentTypeID)
            {
                dt1.Rows.Add(dr.ItemArray);
            }
            
else
            {
                dt2.Rows.Add(dr.ItemArray);
            }
        }

        
for  ( int  j  =   0 ; j  <  dt1.Rows.Count; j ++ )
        {
            DataRow dr 
=  dt1.Rows[j];

            dr[
" TypeName " =  strLeftPre  +  dr[ " TypeName " ].ToString();
            dtTree.Rows.Add(dr.ItemArray);
            
string  strRowParentType  =  dr[ " TypeID " ].ToString();
            fn_ChangeToTree(
ref  dtTree, dt2, intLevel, strRowParentType);
        }
    }
    
#endregion

    
#endregion

 

 

转载于:https://www.cnblogs.com/freeliver54/archive/2011/01/28/1947009.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值