不再为无限级树结构烦恼,且看此篇

7 篇文章 0 订阅
4 篇文章 0 订阅

很久都没有写点什么出来分享了,最近在做多级树的时候,发现来来回回写过很多遍,于是封装成用户控件,以方便日后重复使用.

首先上效果:

我们看到以上2种效果,都是支持任意级的,这里源码中使用的是递归,以便高效的完成HTML的渲染.

下面上代码,代码中解释的都很详细了,我就不再细说.下面将有示例调用演示:

public partial class  UC_MultiLevelTree : System.Web.UI.UserControl
{
    #region 数据相关属性

    /// <summary>
    /// 要绑定的数据源
    /// </summary>
    public DataTable DataSource { get; set; }

    /// <summary>
    /// 多级树显示文本所在列列名
    /// </summary>
    public string TextFeild { get; set; }

    /// <summary>
    /// 多级树单条数据识别列列名(即选择项的值)
    /// </summary>
    public string ValueFeild { get; set; }

    /// <summary>
    /// 多级树层级区别列列名(仅限单个列区分层级)
    /// </summary>
    public string LevelFeild { get; set; }

    /// <summary>
    /// 多级树顶级的父项值
    /// </summary>
    public string TopLevelFeildValue { get; set; }

    #endregion

    #region 显示相关属性

    /// <summary>
    /// 是否显示多选框,默认为显示
    /// </summary>
    public bool ShowCheckBox { get; set; }

    /// <summary>
    /// 是否显示自定义根节点
    /// </summary>
    public bool ShowCustomerRoot { get; set; }

    /// <summary>
    /// 自定义根节点文本
    /// </summary>
    public string CustomerRootText { get; set; }

    /// <summary>
    /// 多级树宽度,可为像素或者百分比
    /// </summary>
    public string Width { get; set; }

    /// <summary>
    /// 多级树高度,可为像素或者百分比
    /// </summary>
    public string Height { get; set; }

    /// <summary>
    /// 展开符号(可为HTML代码)
    /// </summary>
    public string ExtendSign { get; set; }

    /// <summary>
    /// 收缩符号(可为HTML代码)
    /// </summary>
    public string ShrinkSign { get; set; }

    /// <summary>
    /// 每级与上级空格个数
    /// </summary>
    public int LevelSeparatorCount { get; set; }

    /// <summary>
    /// 默认展开级别
    /// </summary>
    public int ExtendLevelNum { get; set; }

    #endregion

    #region 私有变量

    /// <summary>
    /// 扩展标记的HTML
    /// </summary>
    private string StrExtendSign;

    /// <summary>
    /// 收缩标记的HTML
    /// </summary>
    private string StrShrinkSign;

    /// <summary>
    /// 多选框的HTML
    /// </summary>
    private string StrCheckbox;

    /// <summary>
    /// 子层级开始符号的HTML
    /// </summary>
    private string LevelSeparator = " ";

    #endregion


    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.ShowCheckBox = true;
        this.Width = "100%";
        this.Height = "100%";
        this.ExtendSign = "[+]";
        this.ShrinkSign = "[-]";
        this.TopLevelFeildValue = CRMCommon.strNullGuid;
        this.LevelSeparatorCount = 4;
        this.ExtendLevelNum = 2;
    }


    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void DataBind()
    {
        this.StrCheckbox = this.ShowCheckBox ? "<input type='checkbox' class='MLT_Checkbox'/>" : "";
        this.StrExtendSign = "<span class='MLT_ExtendSign' {0}>" + this.ExtendSign + "</span>";
        this.StrShrinkSign = "<span class='MLT_ShrinkSign' {0}>" + this.ShrinkSign + "</span>";
        this.ltMultiLevelTreeHtml.Text = RenderTree(this.TopLevelFeildValue, 1);
    }


    private string RenderTree(string parentValue, int level)
    {
        StringBuilder sb = new StringBuilder();

        string extendSignHtml = "";
        string shrinkSignHtml = "";

        //收缩,展开按钮的显示控制
        if (level < this.ExtendLevelNum)
        {
            extendSignHtml = string.Format(this.StrExtendSign, "style='display:none;'");
            shrinkSignHtml = string.Format(this.StrShrinkSign, "");
        }
        else
        {
            extendSignHtml = string.Format(this.StrExtendSign, "");
            shrinkSignHtml = string.Format(this.StrShrinkSign, "style='display:none;'");
        }

        //自定义根节点
        if (level == 1)
        {
            sb.AppendFormat("<div class='MLT_Panel' style='width:{0};height:{1}'>", this.Width, this.Height);
            if (this.ShowCustomerRoot)
            {
                sb.AppendFormat("<div class='MLT_Item' level='{0}' rel=''>{1}<span class='MLT_Item_Text'>{2}</span></div>", level, extendSignHtml + shrinkSignHtml + this.StrCheckbox, this.CustomerRootText);

                level += 1;
            }
            sb.Append(RenderTree(parentValue, level));
            sb.Append("</div>");
        }

        else if (level != 1)
        {
            //数据项绑定
            if (this.DataSource != null && this.DataSource.Rows.Count > 0)
            {
                string levelSeparator = "";

                if (level > 1)
                {
                    levelSeparator += "<span  class='MLT_LevelSeparator'>";
                    for (int i = 1; i <= (level - 1) * this.LevelSeparatorCount; i++)
                    {
                        levelSeparator += this.LevelSeparator;
                    }
                    levelSeparator += "</span>";
                }

                DataRow[] drList = this.DataSource.Select(string.Format("{0}='{1}'", this.LevelFeild, parentValue));

                if (drList != null && drList.Length > 0)
                {
                    level += 1;
                    foreach (DataRow dr in drList)
                    {
                        string childHtml = RenderTree(dr[ValueFeild].ToString(), level);

                        string signs = string.IsNullOrWhiteSpace(childHtml) ? "<span  class='MLT_ExtendSignPlaceholder'></span>" : extendSignHtml + shrinkSignHtml;

                        sb.AppendFormat("<div class='MLT_Item' level='{0}' rel='{1}' parent='{2}' {3}>{4}<span class='MLT_Item_Text'>{5}</span></div>", level - 1, dr[ValueFeild], dr[LevelFeild], level - 1 > this.ExtendLevelNum ? "style='display:none;'" : "", levelSeparator + signs + this.StrCheckbox, dr[TextFeild]);

                        if (!string.IsNullOrWhiteSpace(childHtml))
                        {
                            sb.Append(childHtml);
                        }
                    }
                }
            }
        }
        return sb.ToString();

    }
}

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UC_MultiLevelTree.ascx.cs" Inherits="UC_MultiLevelTree" %>
<asp:Literal runat="server" ID="ltMultiLevelTreeHtml"></asp:Literal>
<script>
    $(function () {
        $(".MLT_Item").click(function (e) {
            e.stopPropagation();
            $(".MLT_Item").removeClass("MLT_Item_hover");
            $(this).addClass("MLT_Item_hover");
            extendItem(this);
        });

        $(".MLT_ExtendSign").click(function (e) {
            e.stopPropagation();
            var event = e.currentTarget;
            var item = $(event).parent();
            extendItem(item);
        })

        $(".MLT_ShrinkSign").click(function (e) {
            e.stopPropagation();
            var event = e.currentTarget;
            var item = $(event).parent();
            shrinkItem(item);
        })

        $(".MLT_Checkbox").click(function (e) {
            e.stopPropagation();
            var event = e.currentTarget;
            var item = $(event).parent();
            var checked = $(event).attr("checked");
            checkItems(item, checked);
        });
    });

    //展开项
    function extendItem(obj) {
        var rel = $(obj).attr("rel");
        if (rel != undefined && rel.length > 0) {
            $(obj).siblings("div[parent=" + rel + "]").each(function () {
                $(this).show();
            });
        }
        else {
            $(obj).siblings("div[level=2]").show();
        }
        $(obj).find(".MLT_ExtendSign").hide();
        $(obj).find(".MLT_ShrinkSign").show();
    }

    //收缩项
    function shrinkItem(obj) {
        var rel = $(obj).attr("rel");
        if (rel != undefined && rel.length > 0) {
            $(obj).siblings("div[parent=" + rel + "]").each(function () {
                $(this).hide();
                $(this).find(".MLT_ExtendSign").show();
                $(this).find(".MLT_ShrinkSign").hide();
                shrinkItem(this);
            });
        }
        else {
            $(obj).siblings("div[level!=1]").hide();
            $(obj).siblings("div[level!=1]").find(".MLT_ExtendSign").show();
            $(obj).siblings("div[level!=1]").find(".MLT_ShrinkSign").hide();
        }
        $(obj).find(".MLT_ExtendSign").show();
        $(obj).find(".MLT_ShrinkSign").hide();
    }

    //选择项
    function checkItems(obj, checked) {
        var rel = $(obj).attr("rel");
        if (rel != undefined && rel.length > 0) {
            if (checked) {
                $(obj).siblings("div[parent=" + rel + "]").each(function () {
                    $(this).find("input[type=checkbox]").attr("checked", "checked");
                    checkItems(this, checked);
                });
            }
            else {
                $(obj).siblings("div[parent=" + rel + "]").each(function () {
                    $(this).find("input[type=checkbox]").removeAttr("checked");
                    checkItems(this, checked);
                });
            }
        }
        else {
            if (checked) {
                $(obj).parent().find("input[type=checkbox]").attr("checked", "checked");
            }
            else {
                $(obj).parent().find("input[type=checkbox]").removeAttr("checked");
            }
        }
    }
</script>
<style type="text/css">
    .MLT_Panel
    {
        white-space: nowrap;
        overflow: auto;
    }

    .MLT_Item
    {
        font-size: 12px;
        line-height: 20px;
        cursor: pointer;
    }

    .MLT_Item_hover
    {
        background-color: rgb(167, 205, 240);
    }

    .MLT_Item span
    {
        line-height: 20px;
        display: inline-block;
    }

    .MLT_Checkbox
    {
        position: relative;
        width: 12px;
        height: 12px;
        margin: 0 2px;
        bottom: 2px;
    }

    .MLT_ExtendSign, .MLT_ShrinkSign, .MLT_ExtendSignPlaceholder
    {
        font-family: "宋体";
        width: 18px;
        text-align: center;
    }
</style>


 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UC_MultiLevelTree.ascx.cs" Inherits="UC_MultiLevelTree" %>
<asp:Literal runat="server" ID="ltMultiLevelTreeHtml"></asp:Literal>
<script>
    $(function () {
        $(".MLT_Item").click(function (e) {
            e.stopPropagation();
            $(".MLT_Item").removeClass("MLT_Item_hover");
            $(this).addClass("MLT_Item_hover");
            extendItem(this);
        });

        $(".MLT_ExtendSign").click(function (e) {
            e.stopPropagation();
            var event = e.currentTarget;
            var item = $(event).parent();
            extendItem(item);
        })

        $(".MLT_ShrinkSign").click(function (e) {
            e.stopPropagation();
            var event = e.currentTarget;
            var item = $(event).parent();
            shrinkItem(item);
        })

        $(".MLT_Checkbox").click(function (e) {
            e.stopPropagation();
            var event = e.currentTarget;
            var item = $(event).parent();
            var checked = $(event).attr("checked");
            checkItems(item, checked);
        });
    });

    //展开项
    function extendItem(obj) {
        var rel = $(obj).attr("rel");
        if (rel != undefined && rel.length > 0) {
            $(obj).siblings("div[parent=" + rel + "]").each(function () {
                $(this).show();
            });
        }
        else {
            $(obj).siblings("div[level=2]").show();
        }
        $(obj).find(".MLT_ExtendSign").hide();
        $(obj).find(".MLT_ShrinkSign").show();
    }

    //收缩项
    function shrinkItem(obj) {
        var rel = $(obj).attr("rel");
        if (rel != undefined && rel.length > 0) {
            $(obj).siblings("div[parent=" + rel + "]").each(function () {
                $(this).hide();
                $(this).find(".MLT_ExtendSign").show();
                $(this).find(".MLT_ShrinkSign").hide();
                shrinkItem(this);
            });
        }
        else {
            $(obj).siblings("div[level!=1]").hide();
            $(obj).siblings("div[level!=1]").find(".MLT_ExtendSign").show();
            $(obj).siblings("div[level!=1]").find(".MLT_ShrinkSign").hide();
        }
        $(obj).find(".MLT_ExtendSign").show();
        $(obj).find(".MLT_ShrinkSign").hide();
    }

    //选择项
    function checkItems(obj, checked) {
        var rel = $(obj).attr("rel");
        if (rel != undefined && rel.length > 0) {
            if (checked) {
                $(obj).siblings("div[parent=" + rel + "]").each(function () {
                    $(this).find("input[type=checkbox]").attr("checked", "checked");
                    checkItems(this, checked);
                });
            }
            else {
                $(obj).siblings("div[parent=" + rel + "]").each(function () {
                    $(this).find("input[type=checkbox]").removeAttr("checked");
                    checkItems(this, checked);
                });
            }
        }
        else {
            if (checked) {
                $(obj).parent().find("input[type=checkbox]").attr("checked", "checked");
            }
            else {
                $(obj).parent().find("input[type=checkbox]").removeAttr("checked");
            }
        }
    }
</script>
<style type="text/css">
    .MLT_Panel
    {
        white-space: nowrap;
        overflow: auto;
    }

    .MLT_Item
    {
        font-size: 12px;
        line-height: 20px;
        cursor: pointer;
    }

    .MLT_Item_hover
    {
        background-color: rgb(167, 205, 240);
    }

    .MLT_Item span
    {
        line-height: 20px;
        display: inline-block;
    }

    .MLT_Checkbox
    {
        position: relative;
        width: 12px;
        height: 12px;
        margin: 0 2px;
        bottom: 2px;
    }

    .MLT_ExtendSign, .MLT_ShrinkSign, .MLT_ExtendSignPlaceholder
    {
        font-family: "宋体";
        width: 18px;
        text-align: center;
    }
</style>


 

示例:

使用原数据:

生成HTML中,每一级每一条都包含在使用相同class的DIV当中,不同之外在于自定义的level,parent,rel等属性,请参见代码.

下列为调用代码方法,各参数可自行设定,说见用户控件CS代码:

由于时间问题,可能很多地方不便细说.如有更多疑问,请加QQ群:ASP.NET高级群,群号: 261882616

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无限树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值