/////////////// Data table to Json String
///////////////////////// Get data from database
/////////////////////////// Generate Json Stirng
public String Convert_DataTable_jSonString(DataTable dataTable)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();
Dictionary<String, Object> row;
foreach (DataRow dr in dataTable.Rows)
{
row = new Dictionary<String, Object>();
foreach (DataColumn col in dataTable.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
tableRows.Add(row);
}
return
serializer.Serialize(tableRows);
}
public DataTable GetDataTable()
{
DataTable dataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConString"].ConnectionString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "Customer_Search";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City", txtCity.Text);
if (conn.State != ConnectionState.Open)
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dataTable.Load(dr);
}
return
dataTable;
}
/////////////////////////// Generate Json Stirng
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dataTable = GetDataTable();
String jSonString = ConvertDataTableTojSonString(dataTable);
}