C#将datatable生成easyui的绑定tree 的json数据格式

   /// <summary>
    /// 根据DataTable生成Json树结构
    /// </summary>
    /// <param name="tabel">数据源</param>
    /// <param name="idCol">ID列</param>
    /// <param name="txtCol">Text列</param>
    /// <param name="rela">关系字段(字典表中的树结构字段)</param>
    /// <param name="pId">父ID(0)</param>
    StringBuilder result = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    private void GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
    {
        result.Append(sb.ToString());
        sb.Clear();
        if (tabel.Rows.Count > 0)
        {
            sb.Append("[");
            string filer = string.Format("{0}='{1}'", rela, pId);
            DataRow[] rows = tabel.Select(filer);
            if (rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"state\":\"open\"");
                    if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                    {
                        sb.Append(",\"children\":");
                        GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                        result.Append(sb.ToString());
                        sb.Clear();
                    }
                    result.Append(sb.ToString());
                    sb.Clear();
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            result.Append(sb.ToString());
            sb.Clear();
        }
    }

 

 

GetTreeJsonByTable(datatable, "id", "title", "pid", "0");
string content = result.ToString();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值