Tuesday, 25 September 2018

Convert datatable to json in C#

/////////////// Data table to Json String


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);
}


///////////////////////// Get data from database


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);
}

How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...