zoukankan      html  css  js  c++  java
  • C#将datatable生成easyui的绑定tree 的json数据格式

    在用easyui控件的时候常用到他能解析的 接送数据,我们可以通过c#将我们从数据库中得到datatable转换成那样的格式,datagrid的好转换,简单的循环拼串就可以,不过 easyui绑定树的时候的接送数据格式稍有不同,比datagrid和datagridtree得到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</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();
    }
    }

    调用方法很简单,运行这个void 类型的函数,然后取result 的值就行了,

    GetTreeJsonByTable(datatable, "id", "title", "pid", "0");
    string content = result.ToString();



  • 相关阅读:
    centos 安装 TortoiseSVN svn 客户端
    linux 定时任务 日志记录
    centos6.5 安装PHP7.0支持nginx
    linux root 用户 定时任务添加
    composer 一些使用说明
    laravel cookie写入
    laravel composer 安装指定版本以及基本的配置
    mysql 删除重复记录语句
    linux php redis 扩展安装
    linux php 安装 memcache 扩展
  • 原文地址:https://www.cnblogs.com/shenyixin/p/2288033.html
Copyright © 2011-2022 走看看