Here i have explained how to bind Data to Datatable using JSON in Asp.Net C#.

First of all crate a table as shown in below picture.

Step 1) Add HTML:

<table id="tbDetails" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserId</th>
<th>UserName</th>
<th>Location</th>
</tr>
</thead>
</table>

Step 2) JavaScript

Attach following JavaScript file inside head tag

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Add following JavaScript with script tag

$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "practise2.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#tbDetails").append("" + data.d[i].UserId + "" + data.d[i].UserName + "" + data.d[i].Location + "");
}
},
error: function (result) {
alert("Error");
}
});
});

Step 3) CSS

Add following CSS classes with style tag

table { border-collapse: collapse; width:100%; }
table, th {   text-align:left;  background-color:Orange;  }
table, td { background:#fff; }
table, th, td { border: 1px solid black;  padding: 4px 10px 4px 10px; }

Step 4) Namespaces

Import following Namespaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

Step 5) C#

[WebMethod]
   
public static UserDetails[] BindDatatable()
{
DataTable dt = new DataTable();
List details = new List();

string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("select * from table_name", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.UserId = dtrow["UserId"].ToString();
user.UserName = dtrow["UserName"].ToString();
user.Location = dtrow["Location"].ToString();
details.Add(user);
}
}
}
return details.ToArray();
}
public class UserDetails
{
public string UserId { get; set; }
public string UserName { get; set; }
public string Location { get; set; }
}

Screenshot

Add Comments