locked
Clearing out GridView data in between Ajax calls to populate it RRS feed

  • Question

  • User-173333858 posted

    I am making a Javascript Ajax call to a Web Method to populate a Gridview table when pressing Keyboard 'Enter' key and the focus is on a textbox called 'LastName'. Everything works ok for the 1st call, there is also a 'RESET' button on the UI, which clears out data in the Gridview when clicked. But if I call the ajax function once, it populates, and then if i change the TextBox text and hit enter again, the new data gets appended to the old data, and GridView headers are lost. I have pasted sample of code here. Any help will

    <script type="text/javascript">
    $(document).on("keypress", "#cnt_lnm", function (e)
            {
                if (e.keyCode == 13 || e.which == '13')
                {
                    if (($('#cnt_lnm').val() == '') && ($('#cnt_empid').val() == '') && ($('#cnt_fnm').val() == '') && ($('#cnt_email').val() == ''))
                        alert("Please enter atleast 1 field to search.");
                    else if ($('#cnt_lnm').val().length < 3)
                        alert("Please enter a minimum of 3 characters to search.");
                    else
                    {        
    
                        SearchEmp(EmplId, FName, LName, EmailAddr);
                    }
                    
                     e.preventDefault();
    
                }
            });
    
    function SearchEmp(EmplId, FName, LName, EmailAddr) {
    
                var empid = $('#cnt_empid').val();
                var fname = $('#cnt_fnm').val();
                var lname = $('#cnt_lnm').val();
                var email = $('#cnt_email').val();
                alert(LName);
                
                $.ajax({
                    type: "POST",
                    url: "FindEmployee.aspx/Bindemployeetable",
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    async: true,
                    //data: JSON.stringify({ EmplId: $('#cnt_empid').val(), FirstName: $('#cnt_fnm').val(), LastName: $('#cnt_lnm').val(), EmailAddr: $('#cnt_email').val() }), 
                    data: JSON.stringify({ EmplId: EmplId, FirstName: FName, LastName: LName, EmailAddr: EmailAddr }), 
    
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        window.location.href = "Admin_Logout.aspx";
                    },
                    success: function (result) {                  
                       if (result.d.length > 0)
                       {                      
                             var row = $("[id*=grdcoverage] tr:last-child").clone(true);
                             //remove the dummy row we have created
                             $("[id*=grdcoverage] tr:first-child").remove();
    
                             for (var i = 0; i < result.d.length; i++)
                             {
                                 var empid = result.d[i].EmplId;
                                 //alert(empid);
                                 //Set product attributes to the row and add it to the gridview
                                 //$("td", row).eq(0).html(result.d[i].EmplId).wrapInner("<a href='EmplStrMng.aspx?EmplId=3318063'>"); 
                                 $("td", row).eq(0).html("<a href='EmplStrMng.aspx?EmplId="+result.d[i].EmplId+"'>"+result.d[i].EmplId+"</a>");
    
                                 $("td", row).eq(1).html(result.d[i].FirstName);
                                 $("td", row).eq(2).html(result.d[i].LastName);
                                 $("td", row).eq(3).html(result.d[i].EmailAddr); 
                                 $("[id*=grdcoverage]").append(row);
                                 //get the copy of the last row again.
                                 row = $("[id*=grdcoverage] tr:last-child").clone(true);                           
                           }
                           $("[id*=HdPanel]").show();
                       }
                    }
                }); 
    
    </script>
    
    <div style="text-align:center"><em>Please enter field(s) below to lookup an employee.</em></div>
        <br />
    
        <div class="form-horizontal" style="margin:auto; width:65%">
            <div class="row"; style="margin:auto">
                <div class="column"; style="margin:auto">
                        <div class="control-group row-fluid form-inline"; style="margin:auto">
                            <div style="margin:auto; width:40%; font-weight:bold"><label for="LName" class="control-label">Last Name: </label></div>
                            <div class="controls" style="margin:auto; width:40%">    
                                
                                <input type="text" class="form-control" id="cnt_lnm" placeholder="Last Name" runat="server"  clientidmode="Static" />                                            
                            </div>
                        </div>
                    </div>
    
     <div id="EmplList" style="margin-left:auto; margin-right:auto" >
           <br />
            <br />
    
            <asp:HiddenField ID="ShowEmptyGrid" runat="server" Value="0"/> 
    
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel  ID="HdPanel" runat="server" >
                <ContentTemplate>
             <asp:GridView  ID="grdcoverage"  ClientIDMode="Static" CssClass="table tablesorter paginated" runat="server" 
                  AllowSorting="True" AutoGenerateColumns="False" Backcolor="White"
                 EmptyDataText="No data found for given Criteria!" OnDataBound="grdcoverage_DataBound" width="65%" 
                 style="margin-left:auto; margin-right:auto">  
    
                <HeaderStyle CssClass="grid-header" ForeColor="White" HorizontalAlign="Center"/>
                <Columns>    
                         
                    <asp:HyperLinkField DataTextField="EMPLID" HeaderText="EMPL ID" DataNavigateUrlFormatString="~\EmplStrMng.aspx?EMPLID={0}" SortExpression="EMPLID" DataNavigateUrlFields="EMPLID" ItemStyle-Width="15%"
                        ItemStyle-HorizontalAlign="Center">
                                           
                    <ControlStyle Font-Underline="True" />
                    <HeaderStyle Font-Bold="True" Font-Underline="True" HorizontalAlign="Center" />
    <ItemStyle HorizontalAlign="Center" Width="15%" Font-Underline="True"></ItemStyle>
                    </asp:HyperLinkField>
                                           
                    <asp:BoundField DataField="FIRSTNAME" HeaderText="First Name" ItemStyle-HorizontalAlign="Center" SortExpression="FIRSTNAME" ItemStyle-Width="25%" ItemStyle-Wrap="false" >
    <ItemStyle HorizontalAlign="Center" Wrap="False" Width="25%"></ItemStyle>
                    </asp:BoundField>
                    <asp:BoundField DataField="LASTNAME" HeaderText="Last Name" ItemStyle-HorizontalAlign="Center" SortExpression="LASTNAME" ItemStyle-Width="25%" ItemStyle-Wrap="false">
    <ItemStyle HorizontalAlign="Center" Wrap="False" Width="25%"></ItemStyle>
                    </asp:BoundField>
                    <asp:BoundField DataField="EMAILADDR" HeaderText="EMail Address" ItemStyle-HorizontalAlign="Center" SortExpression="EMAILADDR" ItemStyle-Width="35%" ItemStyle-Wrap="false">
                   
    <ItemStyle HorizontalAlign="Center" Wrap="False" Width="35%"></ItemStyle>
                    </asp:BoundField>
                   
                </Columns>
            </asp:GridView> 
                    </ContentTemplate>
                </asp:UpdatePanel>
    
        </div>
       
    </asp:Content>
    
    CODE BEHIND:
     void Page_Load(object sender, EventArgs e)
            {
                //if (Session["LoginEmplId"] == null)
                //{
                //    Response.Redirect("~/Admin_Logout.aspx");
                //}
    
                cnt_lnm.Focus();
                if (grdcoverage.Rows.Count > 0)
                {
                    grdcoverage.UseAccessibleHeader = true;
                    grdcoverage.HeaderRow.TableSection = TableRowSection.TableHeader;
                }
                //Load and empty row to gridview
                if (!IsPostBack)
                {
                    //FixGridHeader();
    
                    List<Models.Employee> data = new List<Models.Employee>();
                    data.Add(new Models.Employee { EmplId = "123456", LastName = "last", FirstName = "First", EmailAddr = "abc@gmail.com" });
                    grdcoverage.DataSource = data;
                    grdcoverage.DataBind();
                    HdPanel.Attributes["style"] = "display:none"; // first hide the updatepanel
                }
    
    [WebMethod(EnableSession = true)]
            public static List<Models.Employee> Bindemployeetable(string EmplId, string FirstName, string LastName, string EmailAddr)
            {
                //FixGridHeader();
                //creating the object of EmployeeRepository class  
                EmployeeRepository repository = new EmployeeRepository();
    
                Models.Employee EmplData = new Models.Employee()
                {
                    //EmplId = HttpContext.Current.Session["emplid"] as String,
                    //FirstName = HttpContext.Current.Session["FName"] as String,
                    //LastName = HttpContext.Current.Session["LName"] as String,
                    //EmailAddr = HttpContext.Current.Session["EMail"] as String,
    
                    EmplId = EmplId as String,
                    FirstName = FirstName as String,
                    LastName = LastName as String,
                    EmailAddr = EmailAddr as String,
                };
    
                List<Models.Employee> empInfo = null;
                empInfo = repository.SearchEmployees(EmplData);
                return (empInfo);
    
            }
    
    public class EmployeeRepository
        {
            string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
    
            //Get Employee Records
            public List<Models.Employee> SearchEmployees(Models.Employee employee)
            {
                var employeeList = new List<Models.Employee>();
                string cmdtxt = string.Empty;
                try
                {
                    // In a using statement, acquire the SqlConnection as a resource.        
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        //call sp
                        SqlCommand command = new SqlCommand("dbo.sp_CVS_Employee_Search", con);
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@EmplId", employee.EmplId);
                        command.Parameters.AddWithValue("@FirstName", employee.FirstName);
                        command.Parameters.AddWithValue("@LastName", employee.LastName);
                        command.Parameters.AddWithValue("@EmailAddr", employee.EmailAddr);
                        //end call sp
                        //open the db connection 
    
    
                        con.Open();
                        SqlDataReader reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            var employeeSet = new Models.Employee()
                            {
                                EmplId = Convert.ToString(reader["EmplId"]),  
                                
                                FirstName = Convert.ToString(reader["First_Name"]),
                                LastName = Convert.ToString(reader["Last_Name"]),
                                EmailAddr = Convert.ToString(reader["Email_Addr"]),
                                
                               // IsChecked = false
                            };
                            employeeList.Add(employeeSet);
                        }
                        //fill the dataaset with adapter data
    
                       // SqlDataAdapter sda = new SqlDataAdapter(command);
                       // DataSet ds = new DataSet();
                       // sda.Fill(ds);
    
                        reader.Close();
                        
                      
                        return employeeList;
                    }
                }
                catch (Exception exception)
                {
                    //throw new NewEmployee(; //HandleError(exception);
                    var error = new Employee() { ErrorMessage = exception.Message };
                    employeeList.Add(error);
                }
                return employeeList;
            }


    be appreciated.

    Friday, May 31, 2019 11:56 AM

Answers

  • User665608656 posted

    Hi RDesh,

    According to your description and the code you provided,I suggest that you clear the data in GridView except the header line and the last line first in the success method of Ajax , so as to ensure that you input other content by pressing enter, and that the new data will not be loaded after the old data.

    Then loop the result.d, and as Bruce said, when you clone the last row of data, you need to delete the last row of data, and then insert the current data line by line.

    For more details,you could refer to the folllwing code:

     success: function (result) {
                        $("[id*=grdcoverage] tr:not(:first):not(:last)").html("");
                        if (result.d.length > 0) {
                            var row = $("[id*=grdcoverage] tr:last-child").clone(true);
                            //remove the dummy row we have created
                            $("[id*=grdcoverage] tr:last-child").remove();
    
                            for (var i = 0; i < result.d.length; i++) {
                                var empid = result.d[i].EmplId;
                                //alert(empid);
                                //Set product attributes to the row and add it to the gridview
                                //$("td", row).eq(0).html(result.d[i].EmplId).wrapInner("<a href='EmplStrMng.aspx?EmplId=3318063'>"); 
                                $("td", row).eq(0).html("<a href='EmplStrMng.aspx?EmplId=" + result.d[i].EmplId + "'>" + result.d[i].EmplId + "</a>");
    
                                $("td", row).eq(1).html(result.d[i].FirstName);
                                $("td", row).eq(2).html(result.d[i].LastName);
                                $("td", row).eq(3).html(result.d[i].EmailAddr);
                                $("[id*=grdcoverage]").append(row);
                                //get the copy of the last row again.
                                row = $("[id*=grdcoverage] tr:last-child").clone(true);
                            }
                            $("[id*=HdPanel]").show();
                        }
                    }

    The result of my work demo:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 3, 2019 5:14 AM

All replies

  • User-474980206 posted
    Your code only deletes the first row, which is the header, then appends rows. You probably wanted to delete all after the first row. Don’t know if gridview build valid tables but normally you just empty the tbody. Also your code won’t work if the table starts empty.
    Friday, May 31, 2019 3:51 PM
  • User665608656 posted

    Hi RDesh,

    According to your description and the code you provided,I suggest that you clear the data in GridView except the header line and the last line first in the success method of Ajax , so as to ensure that you input other content by pressing enter, and that the new data will not be loaded after the old data.

    Then loop the result.d, and as Bruce said, when you clone the last row of data, you need to delete the last row of data, and then insert the current data line by line.

    For more details,you could refer to the folllwing code:

     success: function (result) {
                        $("[id*=grdcoverage] tr:not(:first):not(:last)").html("");
                        if (result.d.length > 0) {
                            var row = $("[id*=grdcoverage] tr:last-child").clone(true);
                            //remove the dummy row we have created
                            $("[id*=grdcoverage] tr:last-child").remove();
    
                            for (var i = 0; i < result.d.length; i++) {
                                var empid = result.d[i].EmplId;
                                //alert(empid);
                                //Set product attributes to the row and add it to the gridview
                                //$("td", row).eq(0).html(result.d[i].EmplId).wrapInner("<a href='EmplStrMng.aspx?EmplId=3318063'>"); 
                                $("td", row).eq(0).html("<a href='EmplStrMng.aspx?EmplId=" + result.d[i].EmplId + "'>" + result.d[i].EmplId + "</a>");
    
                                $("td", row).eq(1).html(result.d[i].FirstName);
                                $("td", row).eq(2).html(result.d[i].LastName);
                                $("td", row).eq(3).html(result.d[i].EmailAddr);
                                $("[id*=grdcoverage]").append(row);
                                //get the copy of the last row again.
                                row = $("[id*=grdcoverage] tr:last-child").clone(true);
                            }
                            $("[id*=HdPanel]").show();
                        }
                    }

    The result of my work demo:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 3, 2019 5:14 AM
  • User-173333858 posted

    Thank you YongQing! Yes, I got it.

    Thank you all, appreciate your replies!

    Wednesday, June 5, 2019 12:22 PM
  • User414668962 posted

    That' cool! This forum is really useful. Thanks!

    Thursday, June 6, 2019 9:55 AM