日期:2014-05-16 浏览次数:20941 次
原来自己写的现在备份一下省的到时候有问题
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.Data.SqlClient; public partial class Station_Name_Data : System.Web.UI.Page { protected string strStation_Name = string.Empty; protected void Page_Load(object sender, EventArgs e) { string Factory_Name = Request.Form["FactoryName"].Trim(); SqlConnection conn_StationName = new SqlConnection(); conn_StationName.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["XNYQFGS"].ConnectionString; try { conn_StationName.Open(); SqlCommand cmd_Station = new SqlCommand(); cmd_Station.Connection = conn_StationName; cmd_Station.CommandText = "select station_id,Station_Name from station_info inner join factory_info on station_info.factory_id=factory_info.factory_id where factory_info.factory_name='" + Factory_Name + "'"; SqlDataAdapter sda = new SqlDataAdapter(cmd_Station); DataSet ds = new DataSet(); sda.Fill(ds); //strCompany_Name += "["; //for (int i = 0; i < ds.Tables[0].Rows.Count; i++) //{ // //最后一条单独处理 // //格式如下: // /* // * [{"serviceHall_Name":"名字1","serviceHall_ID":"1"},{"serviceHall_Name":"名字2","serviceHall_ID":"2"}] // */ // string ID = ds.Tables[0].Rows[i][0].ToString().Trim(); // string Company_Name = ds.Tables[0].Rows[i][1].ToString().Trim(); // strCompany_Name += "'{Company_ID':'" + ID + "',"; // strCompany_Name += "'Company_Name':'" + Company_Name + "'},"; //} //strCompany_Name = strCompany_Name.Remove(strCompany_Name.Length - 1); //strCompany_Name += "]"; DataTable dt = ds.Tables[0]; strStation_Name = DataTableToJson(dt, "rootStationName", 0, dt.Rows.Count); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { conn_StationName.Close(); } HttpContext.Current.Response.Write(strStation_Name); HttpContext.Current.Response.End(); } public static string DataTableToJson(DataTable dt, string strTableName, int start, int limit) { StringBuilder jsonBuilder = new StringBuilder(); string head = "{ success:true,\"totalRecordCount\":\"" + dt.Rows.Count.ToString() + "\",\""; //jsonBuilder.Append("{\""); string tmpStr = ""; jsonBuilder.Append(strTableName); jsonBuilder.Append("\":["); if (dt.Rows.Count > 0) { int endCount = start + limit; if (endCount > dt.Rows.Count) endCount = dt.Rows.Count; for (int i = start; i < endCount; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("\""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("\":\""); tmpStr = dt.Rows[i][j].ToString().Trim(); jsonBuilder.Append(tmpStr.Replace("\"", "\\\""));