简体   繁体   中英

ASP.net Textbox Live Search - GridView Results Filter

My scenario is; I'm trying to do a live search feature for my ASP.net project. In the form, I have a description textbox where the user will type in the search and as the user types in anything, the GridView below filters the results accordingly. I have tried this on desktop applications and it's not much of a hassle but I recently dipped in on Web Applications. Any help would be appreciated. I'm sure there is an easy way to do this but I seem to be having trouble finding "that" way.

Below are what I tried already:

I have tried using onTextChanged property of the textbox but it only populates after the event request.

I have added a function using Ajax+ JQuery which calls the method but the gridview is not displaying the data.

enter code here

<script type="text/javascript">
    $(function () {
        GetCustomers();
    });
    $("[id*=TxtDescription]").live("keyup", function () {
        GetCustomers();
    });

    function SearchTerm() {
        return jQuery.trim($("[id*=TxtDescription]").val());
    };
    function GetCustomers() {
        $.ajax({
            type: "POST",
            url: "frmDrugMaster.aspx/GetCustomers",
            data: '{searchTerm: "' + SearchTerm() + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }
    var row;

function OnSuccess(response) {
 var xmlDoc = $.parseXML(response.d);    
        var xml = $(xmlDoc);
        var customers = xml.find("Drugs");
        alert(customers.length);
        if (row == null) {

            row = $("[id*=gvCustomers] tr:last-child").clone(true);
        }

        $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
        if (customers.length > 0) {
            alert(customers.length);
            $.each(customers, function () {
                var customer = $(this);
                $("td", row).eq(0).html($(this).find("DR_Code").text());
                $("td", row).eq(1).html($(this).find("DR_Description").text());
                $("td", row).eq(2).html($(this).find("DR_UnitDose").text());

                alert($("td", row).eq(0).html($(this).find("DR_Description").text()));
                $("[id*=gvCustomers]").append(row);
                $
                row = $("[id*=gvCustomers] tr:last-child").clone(true); 
});
    } else {
        var empty_row = row.clone(true);
        $("td:first-child", empty_row).attr("colspan", $("td", row).length);
        $("td:first-child", empty_row).attr("align", "center");
        $("td:first-child", empty_row).html("No records found for the search criteria.");
        $("td", empty_row).not($("td:first-child", empty_row)).remove();
        $("[id*=gvCustomers]").append(row);
    }
    };
</script> 

[WebMethod]
        public static string GetCustomers(string searchTerm)



        {
            SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT  a.DR_UNITDOSE, a.DR_CODE, a.DR_DESCRIPTION, a.DR_GENERIC1, a.DR_GENERIC2, a.DR_GENERIC3, a.DR_GENERIC4, a.DR_COSTPRICE, a.DR_SELLPRICE, a.DR_STATUS  FROM DRUGMASTER a, DRUGCATEGORY b  where a.DR_CATEGORY = b.DC_CODE and DR_DESCRIPTION='"+ searchTerm + "'  ", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
           DataTable dt = new DataTable();
            dt.TableName = "Drugs";
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return ds.GetXml();
        } 

I found a solution to this or atleast a sort to workaround it. I used AJAX + JQuery. I just created a web service for the particular page where the text change will be applied. The codes used are as follows. Hope this helps someone:

/*form*/
create a webform with  a textbox and a gridview:

/*Add this script*/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
script type="text/javascript">
        $(function () {
            $("[id*=txtCountry]").on("keyup", function () {
                $.ajax({
                    type: "POST",
                    url: "WebForm2.aspx/GetCustomers",
                    data: '{searchTerm: "' + $(this).val() + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var row;
                        var xmlDoc = $.parseXML(response.d);
                        var xml = $(xmlDoc);
                        var customers = xml.find("Customers");
                        if (row == null) {
                            row = $("[id*=gvCustomers] tr:last-child").clone(true);
                        }
                        $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
                        if (customers.length > 0) { 
$.each(customers, function () {
                                $("td", row).eq(0).html($(this).find("PD_FSTNM").text());
                                $("td", row).eq(1).html($(this).find("PD_GENDER").text());
                                $("[id*=gvCustomers]").append(row);
                                row = $("[id*=gvCustomers] tr:last-child").clone(true);
                            });
                        } else {
                            var empty_row = row.clone(true);
                            $("td:first-child", empty_row).attr("colspan", $("td", row).length);
                            $("td:first-child", empty_row).attr("align", "center");
                            $("td:first-child", empty_row).html("No records found for the search criteria.");
                            $("td", empty_row).not($("td:first-child", empty_row)).remove();
                            $("[id*=gvCustomers]").append(empty_row);
                        }
                    }, 
failure: function (response) { alert(response.d); },

                });
            });
        });
    </script> 

/*C# Code*/
[System.Web.Services.WebMethod]
        public static string GetCustomers(string searchTerm = "")
        {
            string strConnString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            string query = "SELECT * FROM patientdetails";
            if (!string.IsNullOrEmpty(searchTerm))
            {
                query += " WHERE PD_FSTNM LIKE '" + searchTerm + "%'";
            }
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.CommandType = CommandType.Text;

            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds, "Customers");
            return ds.GetXml();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM