当前位置:编程学习 > JS >>

DataTable转为JSON数据格式代码

做项目要用到DataTable转为JSON数据,在前台用ExtJs来操作。所以把这个方法放上来:

 

\代码
1 public static string GetJSON(DataTable dt)
2 {
3 StringBuilder sb = new StringBuilder();
4 sb.Append("{"totalCount":" + dt.Rows.Count + ","data":");
5 sb.Append("[");
6 try
7 {
8 if (dt.Rows.Count > 0)
9 {
10 Hashtable ht = new Hashtable();
11 for (int i = 0; i < dt.Columns.Count; i++)
12 {
13 ht.Add(i, dt.Columns[i].ColumnName);
14 }
15 for (int i = 0; i < dt.Rows.Count; i++)
16 {
17 sb.Append("{");
18 for (int j = 0; j < dt.Columns.Count; j++)
19 {
20 sb.Append(string.Format(""{0}":"{1}",",
21 ht[j], dt.Rows[i][j].ToString()));
22 }
23 sb.Remove(sb.ToString().LastIndexOf(","), 1);
24 sb.Append("},");
25 }
26
补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,