/// <summary>
        /// 根据DataTable生成Json树结构  調用GetTreeJsonByTable(datatable, "MENUID", "MENUNAME", "PARENTID", "0");
        /// </summary>
        /// <param name="tabel">数据源</param>
        /// <param name="idCol">ID列</param>
        /// <param name="txtCol">Text列</param>
        /// <param name="rela">关系字段</param>
        /// <param name="pId">父ID</param>
        ///<returns>easyui tree json格式</returns>
        StringBuilder treeResult = new StringBuilder();
        StringBuilder treesb = new StringBuilder();
        public string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
        {
            string treeJson = string.Empty;
 
            treeResult.Append(treesb.ToString());
            treesb.Clear();
            if (tabel.Rows.Count > 0)
            {
                treesb.Append("[");
 
                string filer = string.Empty;
                if (pId.ToString() == "")
                {
                    filer = string.Format("{0} is null", rela);
                }
                else
                {
                    filer = string.Format("{0}='{1}'", rela, pId);
                }
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        treesb.Append("{\"id\":\"" + row[idCol]
                            + "\",\"text\":\"" + row[txtCol]
                            + "\",\"state\":\"open\"");
 
 
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            treesb.Append(",\"children\":");
                            GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                            treeResult.Append(treesb.ToString());
                            treesb.Clear();
                        }
                        treeResult.Append(treesb.ToString());
                        treesb.Clear();
                        treesb.Append("},");
                    }
                    treesb = treesb.Remove(treesb.Length - 1, 1);
                }
                treesb.Append("]");
                treeResult.Append(treesb.ToString());
                treeJson = treeResult.ToString();
                treesb.Clear();
            }
 
            return treeJson;
        }


调用方法:
MenuTreeHelper treeHelper = new MenuTreeHelper();
return treeHelper.GetTreeJsonByTable(datatable, "ID", "TEXT", "PARENTNO", "0");

posted on 2013-02-05 15:40  liang--liang  阅读(4065)  评论(3编辑  收藏  举报