做項目要用到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