将DataTable生成树json

Posted Debugs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将DataTable生成树json相关的知识,希望对你有一定的参考价值。

protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
ListMenu();
}
}

protected string _menu = string.Empty;
public void ListMenu()
{
StringBuilder sb = new StringBuilder();
DataTable _list = new DataTable();
string ConctionStr = "Data Source=127.0.0.1;Initial Catalog=AccordMenu;Integrated Security=False;User ID=sa;Password=sa";
using (SqlConnection conec = new SqlConnection(ConctionStr))
{
conec.Open();
string SqlText = "SELECT * FROM sys_menu";
SqlCommand Comand = new SqlCommand(SqlText, conec);
SqlDataAdapter Adaper = new SqlDataAdapter(Comand);
Adaper.Fill(_list);
Adaper.Dispose();
Comand.Dispose();
conec.Close();
}
DataRow[] rows = _list.Select("ParentID=0");
sb.Append("[");
bool isFist = false;
foreach (DataRow dr in rows)
{
if (isFist)
sb.Append(",");
isFist = true;
string id = dr["ID"].ToString();
sb.Append("{");
sb.AppendFormat("\"id\":\"{0}\",", dr["ID"]);
sb.AppendFormat("\"text\":\"{0}\",", dr["MenuName"]);
sb.AppendFormat("\"pid\":\"{0}\",", dr["ParentID"]);
sb.AppendFormat("\"iconCls\":\"icon_{0}\",", dr["Menu_ICON"]);
sb.AppendFormat("\"ICON_ID\":\"{0}\",", dr["Menu_ICON"]);
sb.AppendFormat("\"url\":\"{0}\",", dr["Menu_URL"]);
sb.AppendFormat("\"ICON_URL\":\"{0}\"", dr["ICON_URL"]);
sb.Append(",children:[");
sb.Append(GetSubMenu(id, _list));
sb.Append("]");
sb.Append("}");
}
sb.Append("]");
_menu = sb.ToString();

}

/// <summary>
/// 递归调用生成无限级别
/// </summary>
/// <param name="pid"></param>
/// <param name="dt"></param>
/// <returns></returns>
private string GetSubMenu(string pid, DataTable dt)
{
StringBuilder sb = new StringBuilder();
DataRow[] rows = dt.Select("ParentID=" + pid);
if (rows.Length > 0)
{
bool isFist = false;
foreach (DataRow dr in rows)
{
if (isFist)
sb.Append(",");
isFist = true;
string id = dr["ID"].ToString();
sb.Append("{");
sb.AppendFormat("\"id\":\"{0}\",", dr["ID"]);
sb.AppendFormat("\"text\":\"{0}\",", dr["MenuName"]);
sb.AppendFormat("\"pid\":\"{0}\",", dr["ParentID"]);
sb.AppendFormat("\"iconCls\":\"icon_{0}\",", dr["Menu_ICON"]);
sb.AppendFormat("\"ICON_ID\":\"{0}\",", dr["Menu_ICON"]);
sb.AppendFormat("\"url\":\"{0}\",", dr["Menu_URL"]);
sb.AppendFormat("\"ICON_URL\":\"{0}\"", dr["ICON_URL"]);
sb.Append(",children:[");
sb.Append(GetSubMenu(id, dt));
sb.Append("]");
sb.Append("}");
}
}
return sb.ToString();
}
















































































以上是关于将DataTable生成树json的主要内容,如果未能解决你的问题,请参考以下文章

将小计插入动态生成的 DataTable

DataGridView绑定DataTable动态生成列 并且将列名中文显示

如何根据数据表生成脚本? (将 DataTable 转换为 SQL 查询)

将 jQuery DataTable 插件应用于从 ASP.NET 动态生成的表

将 DataTable 保存到数据库表中

ngx-datatable ERESOLVE 无法解析依赖树