17 September 2014

Convert C# DataTable to JavaScript 2D Array

Hi All,

Lets see how to send the DataTable from Code behind to JavaScript.  Some time we face the problem when we need to array the value from C# code behind to JavaScript use use script tag <%=variable_name%> Right we are also going to use the same approach. But the main point is how to convert the DataTable(or Dictionary or List of object) from C# to JavaScript.

Someone might come up with the thought to use the Repeater control.  But its really typical,  What about if I say you can get the C# DataTable  as 2D array in JavaScript with no extra efforts??

:) Cool...

you just need to pass your DataTable in this method and it will create the Json Serialized array to be used in JavaScript. :)

   public partial class RepeaterControlTesting : System.Web.UI.Page
   {
      public string dataTable;        
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            dataTable = ConvertDataTabletoString(getDT());                
         }
      }
      public string ConvertDataTabletoString(DataTable dt)
      {            
          JavaScriptSerializer serializer = new JavaScriptSerializer();
                   
          List<List<object>> rows = new List<List<object>>();
          List<object> row;
          foreach (DataRow dr in dt.Rows)
          {
             row = new List<object>();
             foreach (DataColumn col in dt.Columns)
             {
                row.Add(dr[col]);
             }
             rows.Add(row);
          }

          return serializer.Serialize(rows);
      }
      public DataTable getDT()
      {
          /// or get the DataTable from Database.. 
          DataTable dt = new DataTable();
          dt.Columns.Add("Col_int", typeof (int));
          dt.Columns.Add("Col_string", typeof(string));
          dt.Columns.Add("Col_bool", typeof(bool));
          dt.Columns.Add("Col_4th", typeof(string));
          dt.Columns.Add("Col_float", typeof(float));

          DataRow dr;
          for (int i = 1; i <= 5; i++)
          {
              dr = dt.NewRow();
              dr[0] = i;
              dr[1] = i + "  Col_string";
              dr[2] = (i%2 == 0);
              dr[3] = i + " Col_4th";
              dr[4] = (float)i;

              dt.Rows.Add(dr);
          }

          return dt;
      }

  }

Thats it.. now just goto you aspx file and access the "dataTable" in your JavaScript code..

<body>
    <div id="main">
                
    </div>
        
    <script>        
        var dataTable = <%= this.dataTable %>;
        for (var i = 0; i < dataTable.length; i++) {
            $("#main").append("| "+dataTable[i][0] + " | ");
            $("#main").append(dataTable[i][1] + " | ");
            $("#main").append(dataTable[i][2] + " | ");
            $("#main").append(dataTable[i][3] + " | ");
            $("#main").append(dataTable[i][4] + " |<br/><br/>");
        }
    </script>
</body>



Good to go.. :) Happy Code sharing.. :)

No comments:

Post a Comment