Hi mukesh1,
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="grdchat" runat="server">
</asp:GridView>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetChatDatas",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (r) { alert(r.responseText); }
});
return false;
});
function OnSuccess(response) {
var chatDatas = response.d;
var row = $("[id*=grdchat] tr:last-child").clone(true);
$("[id*=grdchat] tr").not($("[id*=grdchat] tr:first-child")).remove();
for (var i = 0; i < chatDatas.length; i++) {
for (var j = 0; j < chatDatas[i].length; j++) {
$("td", row).eq(j).html(chatDatas[i][j]);
}
row.removeClass();
row.addClass(chatDatas[i][chatDatas[i].length - 1]);
$("[id*=grdchat]").append(row);
row = $("[id*=grdchat] tr:last-child").clone(true);
}
}
</script>
<style type="text/css">
.msg_a
{
position: relative;
background: #FDE4CE;
padding: 10px;
min-height: 10px;
margin-bottom: 5px;
margin-right: 10px;
border-radius: 5px;
width: 170px;
}
.msg_b
{
background: #EEF2E7;
padding: 10px;
min-height: 15px;
margin-bottom: 5px;
position: relative;
margin-left: 10px;
border-radius: 5px;
word-wrap: break-word;
width: 170px;
}
</style>
Namespaces
C#
using System.Data;
using System.Web.Services;
using System.Collections.Generic;
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dummy = new DataTable();
dummy.Columns.Add("message");
dummy.Columns.Add("sender");
dummy.Columns.Add("date");
dummy.Columns.Add("time");
dummy.Columns.Add("direction");
dummy.Rows.Add();
grdchat.DataSource = dummy;
grdchat.DataBind();
}
}
[WebMethod]
public static List<object> GetChatDatas()
{
// Get DataSet from Database.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("message"),
new DataColumn("sender"),
new DataColumn("date"),
new DataColumn("time"),
new DataColumn("direction")});
dt.Rows.Add("ok", "Admin/Manager", "02 Jun 2018", "11:10:03", "msg_a");
dt.Rows.Add("ok", "Admin/Manager", "02 Jun 2018", "11:09:59", "msg_a");
dt.Rows.Add("lets see what they doing", "Admin/Manager", "31 May 2018", "17:22:02", "msg_a");
dt.Rows.Add("this isn not good idea", "Client", "29 May 2018", "12:23:51", "msg_b");
dt.Rows.Add("what ur doing", "Client", "29 May 2018", "12:23:51", "msg_b");
dt.Rows.Add("what ur doing", "Client", "29 May 2018", "10:51:08", "msg_b");
dt.Rows.Add("this isn not good idea", "Admin/Manager", "29 May 2018", "10:51:08", "msg_a");
List<object> chatDatas = new List<object>();
// Add Rows to array.
for (int i = 0; i < dt.Rows.Count; i++)
{
object[] chatData = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
chatData[j] = dt.Rows[i][j];
}
chatDatas.Add(chatData);
}
return chatDatas;
}
Screenshot