Treeview无限分类解决方案

数据表:

CREATE TABLE CateTable (

       [ID] [int] IDENTITY (1, 1) NOT NULL ,

       [CateName] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,

       [RootID] [int] NOT NULL ,

       [ParentID] [int] NOT NULL

)

GO 

存储过程:

CREATE PROCEDURE CateTable_GetList AS

BEGIN

       Select CateID, CateName, RootID, ParentID  From CateTable Order By CateID,RootID,ParentID

END

代码:

private   void  MainForm_Load( object  sender, EventArgs e)
        
{
            
//从数据库中读取数据
            SqlConnection con = new SqlConnection(ConnString.ConStr);
            SqlCommand cmd 
= new SqlCommand("CateTable_GetList", con);
            cmd.CommandType 
= CommandType.StoredProcedure;
            SqlDataAdapter sda 
= new SqlDataAdapter(cmd);
            DataSet ds 
= new DataSet();
            
try
            
{
             sda.Fill(ds);
            }

            
catch
            
{
            }

            
finally
            
{
             cmd 
= null;
             con.Close();
            }

            
//往TreeView中添加树节点
            
//添加根节点
            TreeNode tn = new TreeNode();
            tn.Text 
= "种类";
            tn.Name 
= "0";//Name作为ID
            tn.Tag = "0";//Tag作为RootID
            tn.ImageIndex = 0;
            tn.SelectedImageIndex 
= 0;
            tv.Nodes.Add(tn);
//该TreeView命名为tv
            tv.SelectedNode = tv.TopNode;
            
//把其他节点加上去
            if (ds != null)
            
{
                
foreach (DataRow dr in ds.Tables[0].Rows)
                
{
                    tn 
= new TreeNode();
                    tn.Text 
= dr["CateName"].ToString();
                    tn.Name 
= dr["CateID"].ToString();//Name作为CateID
                    tn.Tag = dr["RootID"].ToString();//Tag作为RootID
                    tn.ImageIndex = 1;
                    tn.SelectedImageIndex 
= 1;
              
//判断是否为主节点
                    if (dr["CateID"].ToString() == dr["RootID"].ToString())
                    
{
               
//主节点
                        tv.SelectedNode = tv.TopNode;
                    }

                    
else
                    
{
               
//其他节点
                        if (tv.SelectedNode.Name != dr["ParentID"].ToString())
                        
{
                            TreeNode[] tn_temp 
= tv.Nodes.Find(dr["ParentID"].ToString(), true);
                            
if (tn_temp.Length > 0)
                            
{
                                tv.SelectedNode 
= tn_temp[0];
                            }

                        }

                    }

                    tv.SelectedNode.Nodes.Add(tn);
                }

                tv.ExpandAll();
//展开TreeView
                tv.SelectedNode = tv.TopNode;
            }

        }

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值