locked
JQuery inserting and binding gridview problem RRS feed

  • Question

  • User-2108448128 posted

    Hi!

    I am trying to insert a row using jquery into my database dable witch has three columns with UserId(set identity true),Name,Lastname and trying to bind the grid by appending the row with jquery too but I have   a problem with the UserId witch get dublicated(I have to refresh dhe page to get the data show correctly)

    My question is how to add the new UserId witch is +1 for every row and not copy the UserId of the old row?

    Result

    Result Image

    Code

        <script type="text/javascript">
           
            function AppendRow(row, UserId, name, country) {
                //Bind CustomerId.
                $(".UserId", row).find("span").html(UserId);
    
                //Bind Name.
                $(".Name", row).find("span").html(name);
                $(".Name", row).find("input").val(name);
    
                //Bind Country.
                $(".Lastname", row).find("span").html(country);
                $(".Lastname", row).find("input").val(country);
    
    
                $("[id*=gvCustomers]").append(row);
            }
    
           
            $(document).ready(function () {
                $("#Button1").click(function () {
                    var txtName = $("[id*=txtName]");
                    var txtCountry = $("[id*=txtCountry]");
                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/InsertCustomer",
                        data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            var row = $("[id*=gvCustomers] tr:last-child");
                            if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != "&nbsp;") {
                                row = row.clone();
                            }
                            AppendRow(row, response.d, txtName.val(), txtCountry.val());
                            txtName.val("");
                            txtCountry.val("");
                        }
                    });
                    return false;
                });
            });
           
    
          
    </script>
         <script type="text/javascript">
    
             $(function () {
                 $.ajax({
                     type: "POST",
                     url: "Default.aspx/GetCustomers",
                     data: '{}',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: OnSuccess,
                     failure: function (r) {
                         alert(r.d);
                     },
                     error: function (response) {
                         alert(r.d);
                     }
                 });
                 // return false;
    
             });
    
    
             function OnSuccess(r) {
                 /
                 var customers = $($.parseXML(r.d)).find("Table");
    
                 
                 var table = $("[id*=gvCustomers]");
    
                
                 var row = table.find("tr:last-child").clone(true);
    
                 
                 $("tr", table).not($("tr:first-child", table)).remove();
    
                
                 $.each(customers, function () {
                     var customer = $(this);
                     $("td", row).eq(0).html($(this).find("UserId").text());
                     $("td", row).eq(1).html($(this).find("Name").text());
                     $("td", row).eq(2).html($(this).find("Lastname").text());
                     table.append(row);
                     row = table.find("tr:last-child").clone(true);
                 });
             }
            </script>

    C# code

     public static string GetCustomers()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT UserId,Name,Lastname FROM " + "dbo.Users";
                        cmd.Connection = con;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataSet ds = new DataSet();
                            sda.Fill(ds);
                            return ds.GetXml();
                        }
                    }
                }
            }
            [WebMethod]
            public static int InsertCustomer(string name, string country)
            {
                using (SqlConnection constr = new SqlConnection("Data Source=(localdb)\\ProjectsV13;Initial Catalog=InventorySysDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
                {
    
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO Users" + " (Name,Lastname,Email,Username,UserRole,Password,RegisteredDate) VALUES (@Name,@Lastname,@Email,@Username,@UserRole,@Password,@RegisteredDate) ", constr))
                    {
    
                        cmd.Parameters.AddWithValue("@Name", name.Trim());
                        cmd.Parameters.AddWithValue("@Lastname", country.Trim());
                        cmd.Parameters.AddWithValue("@Email", "Gab");
                        cmd.Parameters.AddWithValue("@Username", "Gab");
                        cmd.Parameters.AddWithValue("@UserRole", 1);
                        cmd.Parameters.AddWithValue("@Password", "Gab");
                        cmd.Parameters.AddWithValue("@RegisteredDate", DateTime.Now);
    
    
                       
                            constr.Open();
                        int UserId = Convert.ToInt32(cmd.ExecuteScalar());
                        constr.Close();
                        return UserId;
    
                       
                        
    
                    }
                }
    
    
    
    
            }

    Tuesday, March 10, 2020 12:00 AM

Answers

  • User-1330468790 posted

    Hi, ai3231,

     

    From my understanding, your problem is that it always appends the last row's clone to the table after you clicking the button "Button1".

     

    Here are mainly two problems in your code that fails your doing that.

    Problems:

    1.You wrongly use the "insert" command so that it will never return you with the newly incremented "UserId". Instead, you should append a piece of SQL code

    "SELECT @@IDENTITY"

    2.The javascript function does not execute as you expected. Though I don't know what your HTML markups are, it could be detected from above code that you don't have <span> or <input> inside the row.

    Therefore, the function 

    AppendRow(row, UserId, name, country)

    does nothing but append the clone of the row to the row.

      

    Solution is constructed based on the solving above problems.

    More details, please refer to below code: 

    Please focus on the content in yellow background which means I made modification there. 

    Script:

    <script type="text/javascript">
    
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "ManuallyBindToGV.aspx/GetCustomers",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (r) {
                        alert(r.d);
                    },
                    error: function (response) {
                        alert(r.d);
                    }
                });
                // return false;
    
            });
            function OnSuccess(r) {
    
                var customers = $($.parseXML(r.d)).find("Table");
    
    
                var table = $("[id*=gvCustomers]");
    
    
                var row = table.find("tr:last-child").clone(true);
    
    
                $("tr", table).not($("tr:first-child", table)).remove();
    
    
                $.each(customers, function () {
                    var customer = $(this);
                    $("td", row).eq(0).html($(this).find("UserId").text());
                    $("td", row).eq(1).html($(this).find("Name").text());
                    $("td", row).eq(2).html($(this).find("Country").text());
                    table.append(row);
                    row = table.find("tr:last-child").clone(true);
                });
            }
        </script>
        <script type="text/javascript">
    
            function AppendRow(row, UserId, name, country) {
                //populate the data same as onSuccess function
                row.children().eq(0).html(UserId);
                row.children().eq(1).html(name);
                row.children().eq(2).html(country);
    
                $("[id*=gvCustomers]").append(row);
            }
    
            $(document).ready(function () {
                $("#Button1").click(function () {
                    var txtName = $("[id*=txtName]");
                    var txtCountry = $("[id*=txtCountry]");
    $.ajax({ type: "POST", url: "ManuallyBindToGV.aspx/InsertCustomer", data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }', contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log(response.d); debugger; var row = $("[id*=gvCustomers] tr:last-child"); if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != "&nbsp;") { row = row.clone(); } AppendRow(row, response.d, txtName.val(), txtCountry.val()); txtName.val(""); txtCountry.val(""); } }); return false; }); }); </script>

    .aspx Page:

    <form id="form1" runat="server">
            <div>
                <table id="gvCustomers">
                    <tr>
                        <td>UserID</td>
                        <td>Name</td>
                        <td>Country</td>
                    </tr>
                </table>
            </div>
            <div>
                <div>
                    <label for="txtName">Name:</label><input type="text" id="txtName" />
                 </div>
                <div>
                    <label for="txtCountry">Country:</label><input type="text" id="txtCountry" />
                </div>
                <div>
                    <input type="button" id="Button1" value="Add"/>
                </div>
                
                
            </div>
        </form>

    Code behind:

    [WebMethod]
            public static string GetCustomers()
            {
                string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT UserId,Name,Country FROM [Users]";
                        cmd.Connection = con;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataSet ds = new DataSet();
                            sda.Fill(ds);
                            return ds.GetXml();
                        }
                    }
                }
            }
    
            [WebMethod]
            public static int InsertCustomer(string name, string country)
            {
                string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
    
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO [Users] (Name,Country) VALUES (@Name,@Country);SELECT @@IDENTITY; ", con))
                    {
    
                        cmd.Parameters.AddWithValue("@Name", name.Trim());
                        cmd.Parameters.AddWithValue("@Country", country.Trim());
    
    
                        con.Open();
                        int UserId = Convert.ToInt32(cmd.ExecuteScalar());
                        con.Close();
                        return UserId;
    
                    }
                }
            }

     

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 10, 2020 7:53 AM
  • User-2108448128 posted

    I found the answer

    Removed response.d from the append row

    AppendRow(row, txtName.val(), txtCountry.val(), email.val(), username.val(), userrole.val(), password.val(), registereddate.val());

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 12, 2020 6:24 PM

All replies

  • User-37275327 posted

    This is because you are appending the row with out knowing the newly inserted user id. Get the user id from the db, before appending the new row to the grid or get all user records from db and bind the grid.

    Tuesday, March 10, 2020 7:14 AM
  • User-1519014291 posted

    Hi ai3231,

    Please put the primary key or unique index on the UuserID column to prevent it from happen duplicate rows

    for example

    Create table Users (
    UserId int identity(1,1) primary key not null,
    [Name] nvarchar(10),
    Lastname nvarchar(10)
    )
    
    --- OR SETTING UNIQUE CONSTRAINT
    
    CONSTRAINT CONSTR_UserId UNIQUE(TransactionID) 
    
    
    Create table Users (
    UserId int identity(1,1) not null,
    [Name] nvarchar(10),
    Lastname nvarchar(10),
    CONSTRAINT CONSTR_UserId UNIQUE(UserId)
    )

    Add this under the button

      e.preventDefault();
    $("#Button1").click(function(e) {
    
    //Add preventDefault() here
    
     e.preventDefault();
    
    
    
                    var txtName = $("[id*=txtName]");
                    var txtCountry = $("[id*=txtCountry]");
                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/InsertCustomer",
                        data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            var row = $("[id*=gvCustomers] tr:last-child");
                            if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != "&nbsp;") {
                                row = row.clone();
                            }
                            AppendRow(row, response.d, txtName.val(), txtCountry.val());
                            txtName.val("");
                            txtCountry.val("");
                        }
                    });
                    return false;
                });

    Tuesday, March 10, 2020 7:39 AM
  • User-1330468790 posted

    Hi, ai3231,

     

    From my understanding, your problem is that it always appends the last row's clone to the table after you clicking the button "Button1".

     

    Here are mainly two problems in your code that fails your doing that.

    Problems:

    1.You wrongly use the "insert" command so that it will never return you with the newly incremented "UserId". Instead, you should append a piece of SQL code

    "SELECT @@IDENTITY"

    2.The javascript function does not execute as you expected. Though I don't know what your HTML markups are, it could be detected from above code that you don't have <span> or <input> inside the row.

    Therefore, the function 

    AppendRow(row, UserId, name, country)

    does nothing but append the clone of the row to the row.

      

    Solution is constructed based on the solving above problems.

    More details, please refer to below code: 

    Please focus on the content in yellow background which means I made modification there. 

    Script:

    <script type="text/javascript">
    
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "ManuallyBindToGV.aspx/GetCustomers",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (r) {
                        alert(r.d);
                    },
                    error: function (response) {
                        alert(r.d);
                    }
                });
                // return false;
    
            });
            function OnSuccess(r) {
    
                var customers = $($.parseXML(r.d)).find("Table");
    
    
                var table = $("[id*=gvCustomers]");
    
    
                var row = table.find("tr:last-child").clone(true);
    
    
                $("tr", table).not($("tr:first-child", table)).remove();
    
    
                $.each(customers, function () {
                    var customer = $(this);
                    $("td", row).eq(0).html($(this).find("UserId").text());
                    $("td", row).eq(1).html($(this).find("Name").text());
                    $("td", row).eq(2).html($(this).find("Country").text());
                    table.append(row);
                    row = table.find("tr:last-child").clone(true);
                });
            }
        </script>
        <script type="text/javascript">
    
            function AppendRow(row, UserId, name, country) {
                //populate the data same as onSuccess function
                row.children().eq(0).html(UserId);
                row.children().eq(1).html(name);
                row.children().eq(2).html(country);
    
                $("[id*=gvCustomers]").append(row);
            }
    
            $(document).ready(function () {
                $("#Button1").click(function () {
                    var txtName = $("[id*=txtName]");
                    var txtCountry = $("[id*=txtCountry]");
    $.ajax({ type: "POST", url: "ManuallyBindToGV.aspx/InsertCustomer", data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }', contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log(response.d); debugger; var row = $("[id*=gvCustomers] tr:last-child"); if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != "&nbsp;") { row = row.clone(); } AppendRow(row, response.d, txtName.val(), txtCountry.val()); txtName.val(""); txtCountry.val(""); } }); return false; }); }); </script>

    .aspx Page:

    <form id="form1" runat="server">
            <div>
                <table id="gvCustomers">
                    <tr>
                        <td>UserID</td>
                        <td>Name</td>
                        <td>Country</td>
                    </tr>
                </table>
            </div>
            <div>
                <div>
                    <label for="txtName">Name:</label><input type="text" id="txtName" />
                 </div>
                <div>
                    <label for="txtCountry">Country:</label><input type="text" id="txtCountry" />
                </div>
                <div>
                    <input type="button" id="Button1" value="Add"/>
                </div>
                
                
            </div>
        </form>

    Code behind:

    [WebMethod]
            public static string GetCustomers()
            {
                string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT UserId,Name,Country FROM [Users]";
                        cmd.Connection = con;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataSet ds = new DataSet();
                            sda.Fill(ds);
                            return ds.GetXml();
                        }
                    }
                }
            }
    
            [WebMethod]
            public static int InsertCustomer(string name, string country)
            {
                string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
    
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO [Users] (Name,Country) VALUES (@Name,@Country);SELECT @@IDENTITY; ", con))
                    {
    
                        cmd.Parameters.AddWithValue("@Name", name.Trim());
                        cmd.Parameters.AddWithValue("@Country", country.Trim());
    
    
                        con.Open();
                        int UserId = Convert.ToInt32(cmd.ExecuteScalar());
                        con.Close();
                        return UserId;
    
                    }
                }
            }

     

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 10, 2020 7:53 AM
  • User-2108448128 posted

    Thanks for your time it was the function that was appending the row and now is ok.

    Tuesday, March 10, 2020 12:04 PM
  • User-2108448128 posted

    Ps. how to always hide the first row witch is the id row?

    Tuesday, March 10, 2020 2:44 PM
  • User-1330468790 posted

    Hi, ai3231,

    You can just simply add "display:none" for the first column.

    In Jquery, the function is ".css(cssProperty, propertValue);"

    Modification in HTML:

    <table id="gvCustomers">
                    <tr>
                        <td style="display:none">UserID</td>
                        <td>Name</td>
                        <td>Country</td>
                    </tr>
                </table>

    Modification in JS:

    function OnSuccess(r) {
    
                var customers = $($.parseXML(r.d)).find("Table");
    
    
                var table = $("[id*=gvCustomers]");
    
    
                var row = table.find("tr:last-child").clone(true);
    
    
                $("tr", table).not($("tr:first-child", table)).remove();
    
    
                $.each(customers, function () {
                    var customer = $(this);
                    $("td", row).eq(0).css("display","none").html($(this).find("UserId").text());
                    $("td", row).eq(1).html($(this).find("Name").text());
                    $("td", row).eq(2).html($(this).find("Country").text());
                    table.append(row);
                    row = table.find("tr:last-child").clone(true);
                });
            }

    Hope this can help you.

    Best regards,

    Sean

    Thursday, March 12, 2020 11:09 AM
  • User-2108448128 posted

    I tried it and on binding the grid now works and the column is hiding but when i insert a new row I think is shifting the columns on the right

    Check the photo

    code

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default1.aspx.cs" Inherits="WebApplication3.Default1" %>
    
    <!DOCTYPE html>
     <link rel="stylesheet" type="text/css" href="../Stylesheet/GridView1.css"/> 
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
       
    </head>
         
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        
       
        <script type="text/javascript">
           
            function AppendRow(row, UserId, Name, Lastname, Email,Username,UserRole,Password,RegisteredDate) {
                row.children().eq(0).html(UserId);
                row.children().eq(1).html(Name);
                row.children().eq(2).html(Lastname);
                row.children().eq(3).html(Email);
                row.children().eq(4).html(Username);
                row.children().eq(5).html(UserRole);
                row.children().eq(6).html(Password);
                row.children().eq(7).html(RegisteredDate);
    
                $("[id*=gvCustomers]").append(row);
            }
    
            //Add event handler.
            $(document).ready(function () {
                $("#Button1").click(function () {
                    var txtName = $("[id*=txtName]");
                    var txtCountry = $("[id*=txtCountry]");
                    var email = $("[id*=email]");
                    var username = $("[id*=username]");
                    var userrole = $("[id*=userrole]");
                    var password = $("[id*=password]");
                   
                   
                    var registereddate = $("[id*=registereddate]").val(getdatetime(new Date()));
                    $.ajax({
                        type: "POST",
                        url: "Default1.aspx/InsertCustomer",
                        data: '{Name: "' + txtName.val() + '", Lastname: "' + txtCountry.val() + '", Email: "' + email.val() + '", Username: "' + username.val() + '", UserRole: "' + userrole.val() + '", Password: "' + password.val() + '", RegisteredDate: "' + registereddate.val() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            var row = $("[id*=gvCustomers] tr:last-child");
                            if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != "&nbsp;") {
    
                                row = row.clone();
                                
                            }
                            
                            AppendRow(row, response.d, txtName.val(), txtCountry.val(), email.val(), username.val(), userrole.val(), password.val(), registereddate.val());
    
                           
                            txtName.val("");
                            txtCountry.val("");
                            email.val("");
                            username.val("");
                            userrole.val("");
                            password.val("");
                            registereddate.va("");
                        }
                    });
                    return false;
                });
            });
           
            function getdatetime(dt) {
                var res = "";
                res += parseInt(formatdigits(dt.getMonth() + 1),10);
                res += "/";
                res += formatdigits(dt.getDate());
                res += "/";
                res += formatdigits(dt.getFullYear());
                res += " ";
                res += parseInt(formatdigits(dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours()),10);
                res += ":";
                res += formatdigits(dt.getMinutes());
                res += ":";
                res += formatdigits(dt.getSeconds());
                res += " " + dt.getHours() > 11 ? " PM" : " AM";
                return res;
            }
            function formatdigits(val) {
                val = val.toString();
                return val.length == 1 ? "0" + val : val;
            }
          
    </script>
         <script type="text/javascript">
    
             $(function () {
                 $.ajax({
                     type: "POST",
                     url: "Default1.aspx/BindGrid",
                     data: '{}',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: OnSuccess,
                     failure: function (r) {
                         alert(r.d);
                     },
                     error: function (response) {
                         alert(r.d);
                     }
                 });
                 // return false;
    
             });
            
    
    
    
             function OnSuccess(r) {
                 //Parse the XML and extract the records.
                 var customers = $($.parseXML(r.d)).find("Table");
    
                 //Reference GridView Table.
                 var table = $("[id*=gvCustomers]");
    
                 //Reference the Dummy Row.
                 var row = table.find("tr:last-child").clone(true);
    
                 //Remove the Dummy Row.
                 $("tr", table).not($("tr:first-child", table)).remove();
    
               
                 
                 //Loop through the XML and add Rows to the Table.
                 $.each(customers, function () {
                     var customer = $(this);
                     $("td", row).eq(0).css("display", "none").html($(this).find("UserId").text());
                     $("td", row).eq(1).html($(this).find("Name").text());
                     $("td", row).eq(2).html($(this).find("Lastname").text());
                     $("td", row).eq(3).html($(this).find("Email").text());
                     $("td", row).eq(4).html($(this).find("Username").text());
                     $("td", row).eq(5).html($(this).find("UserRole").text());
                     $("td", row).eq(6).html($(this).find("Password").text());
                     $("td", row).eq(7).html($(this).find("RegisteredDate").text());
                     table.append(row);
                     row = table.find("tr:last-child").clone(true);
                 });
               
             }
            </script>
    
        
    <body>
        <form id="form1" runat="server">
            <div>
    
    
                <asp:GridView ID="gvCustomers" runat="server"  AutoGenerateColumns="False"   
            
                                                     >
        <Columns>
            <asp:TemplateField HeaderText="UserId" visible="false"  ItemStyle-Width="110px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("UserId") %>' runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
    
    
            <asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Name") %>' runat="server" />            
                </ItemTemplate>
            </asp:TemplateField>
    
    
            <asp:TemplateField HeaderText="Lastname" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Lastname") %>' runat="server" />             
                </ItemTemplate>
            </asp:TemplateField>
    
    
    
              <asp:TemplateField HeaderText="Email" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Email") %>' runat="server" />        
                </ItemTemplate>
            </asp:TemplateField>
    
    
               <asp:TemplateField HeaderText="Username" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Username") %>' runat="server" />   
                </ItemTemplate>
            </asp:TemplateField>
    
               <asp:TemplateField HeaderText="User Role" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("UserRole") %>' runat="server" />               
                </ItemTemplate>
            </asp:TemplateField>
    
    
    
               <asp:TemplateField HeaderText="Password" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Password") %>' runat="server" />                
                </ItemTemplate>
            </asp:TemplateField>
    
    
                  <asp:TemplateField HeaderText="Registered Date" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:Label Text='<%#Eval("RegisteredDate")%>' runat="server" />                
                </ItemTemplate>       
                       </asp:TemplateField>
    
           
    
    
    
          
        </Columns>
    </asp:GridView>
    
    
                 <asp:TextBox ID="txtName" runat="server" Width="140" />
                 <asp:TextBox ID="txtCountry" runat="server" Width="140" />
                <asp:TextBox ID="email" runat="server"></asp:TextBox>
                <asp:TextBox ID="username" runat="server"></asp:TextBox>
                <asp:TextBox ID="userrole" runat="server"></asp:TextBox>
                <asp:TextBox ID="password" runat="server"></asp:TextBox>
                  <asp:TextBox ID="registereddate"  runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server"  Text="Button"  />
            </div>
          
            
          
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
          
        </form>
    </body>
    </html>

    I think somethingis wrong here

      <script type="text/javascript">
           
            function AppendRow(row, UserId, Name, Lastname, Email,Username,UserRole,Password,RegisteredDate) {
                row.children().eq(0).html(UserId);
                row.children().eq(1).html(Name);
                row.children().eq(2).html(Lastname);
                row.children().eq(3).html(Email);
                row.children().eq(4).html(Username);
                row.children().eq(5).html(UserRole);
                row.children().eq(6).html(Password);
                row.children().eq(7).html(RegisteredDate);
    
                $("[id*=gvCustomers]").append(row);
            }
    
            //Add event handler.
            $(document).ready(function () {
                $("#Button1").click(function () {
                    var txtName = $("[id*=txtName]");
                    var txtCountry = $("[id*=txtCountry]");
                    var email = $("[id*=email]");
                    var username = $("[id*=username]");
                    var userrole = $("[id*=userrole]");
                    var password = $("[id*=password]");
                   
                   
                    var registereddate = $("[id*=registereddate]").val(getdatetime(new Date()));
                    $.ajax({
                        type: "POST",
                        url: "Default1.aspx/InsertCustomer",
                        data: '{Name: "' + txtName.val() + '", Lastname: "' + txtCountry.val() + '", Email: "' + email.val() + '", Username: "' + username.val() + '", UserRole: "' + userrole.val() + '", Password: "' + password.val() + '", RegisteredDate: "' + registereddate.val() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            var row = $("[id*=gvCustomers] tr:last-child");
                            if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != "&nbsp;") {
    
                                row = row.clone();
                                
                            }
                            
                            AppendRow(row, response.d, txtName.val(), txtCountry.val(), email.val(), username.val(), userrole.val(), password.val(), registereddate.val());
    
                           
                            txtName.val("");
                            txtCountry.val("");
                            email.val("");
                            username.val("");
                            userrole.val("");
                            password.val("");
                            registereddate.va("");
                        }
                    });
                    return false;
                });
            });

    Thursday, March 12, 2020 3:40 PM
  • User-2108448128 posted

    I found the answer

    Removed response.d from the append row

    AppendRow(row, txtName.val(), txtCountry.val(), email.val(), username.val(), userrole.val(), password.val(), registereddate.val());

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 12, 2020 6:24 PM
  • User-2108448128 posted

    Another problem came out now with pagesize

    I have page size = 12 and when i add the 13 row the table shift the data in the footer pager

    image check

    How to solve this?

    Friday, March 13, 2020 11:33 AM
  • User-1330468790 posted

    Hi, ai3231,

    It seems a new issue so that I suggest you post the follow up problem in a new thread since you mark the answer for the previous problem and people will be confused for the coming question without a problem context.

    Posting the code and question related to the follow up issue will be much helpful to get a more accurate problem solving.

    Best regards,

    Sean

    Sunday, March 15, 2020 7:04 AM