欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.Net中实现无限分类的2个例子

程序员文章站 2024-02-21 21:51:40
以前总想着搞这个无限分类,今天终于得空好好的看了下,发现实现的原理还是很简单的,数据结构上,用两列(分类编号,上级编号)就可以实现,可是为了联合查询的方便,一般都再增加一列...

以前总想着搞这个无限分类,今天终于得空好好的看了下,发现实现的原理还是很简单的,数据结构上,用两列(分类编号,上级编号)就可以实现,可是为了联合查询的方便,一般都再增加一列(深度),在这个实例里,我只用了两列,剩下的无非就是递归着对treeview进行数据绑定而已~~。

复制代码 代码如下:

 public partial class _default : system.web.ui.page
    {
        bil bil = new bil();
        protected void page_load(object sender, eventargs e)
        {
            if (!ispostback)
            {
                bind_tree("0",null);
            }
        }
        protected void bind_tree(string childnode,treenode tn)
        {
            datatable dt = bil.getbyclasspre(childnode).tables[0];

            foreach (datarow dr in dt.rows)
            {
                treenode node = new treenode();
                if (tn==null)
                {
                    //根
                    node.text = dr["classname"].tostring();
                    this.treeview1.nodes.add(node);
                    bind_tree(dr["classid"].tostring(), node);
                }
                else
                {
                    //当前节点的子节点
                    node.text = dr["classname"].tostring();
                    tn.childnodes.add(node);
                    bind_tree(dr["classid"].tostring(),node);
                }
            }
        }
    }

上次写了使用treeview控件进行无限分类绑定的方法,这回再写个通用性更好的~~嘿嘿 绑定dropdownlist~~思想跟上篇日志很接近,也是使用递归,当然,网络上还有很多人给数据库增加了一个“depth(深度)”的字段,这样进行绑定的时候还可以更简单些哈~~当然,没有必要的就不加了,还是递归使用起来简单些哈~~不多说了,上代码哈:

复制代码 代码如下:

protected void bind_droplist(string childnode, string tmp)
        {
            datatable dt = bil.getbyclasspre(childnode).tables[0];

            foreach (datarow dr in dt.rows)
            {
                if (dr["classpre"].tostring()=="0")
                {
                    //如果是根节点
                    tmp = "";
                    dropdownlist1.items.add(dr["classname"].tostring());
                    bind_droplist(dr["classid"].tostring(), tmp + " ");
                }
                else
                {
                    //不是根节点
                    dropdownlist1.items.add( tmp+"|-" + dr["classname"].tostring());
                    bind_droplist(dr["classid"].tostring(), tmp + " ");
                }
            }
        }