Search record in ASP.Net ListBox while typing using jQuery Ajax

Bhavesh23
 
on Jul 02, 2021 01:21 AM
Sample_998869.zip
2965 Views

in my web project i have used UpdatePanel for some area.

i want to search record in Listbox Using Textbox.

when i start typing in textbox record should be start to display in listbox related textbox value.

but its not working properly. and i need to click in Listbox Record and need to press enter Key.

Below is my code.

SqlConnection con = new SqlConnection(this.con);
con.Open();
SqlCommand cmd = new SqlCommand("Select V_ID from V_TEST Where V_PHONE='" + txtsearchmono.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ListBox1.DataSource = dt;
ListBox1.DataBind();
con.Close();

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 02, 2021 04:44 AM
on Jul 03, 2021 02:18 AM

Hi Bhavesh23,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:TextBox runat="server" ID="txtCategory" CssClass="form-control" /><br />
        <asp:ListBox runat="server" ID="lstCategories" CssClass="form-control"></asp:ListBox>
    </ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        GetCategories();
        $("[id*=txtCategory]").on("keyup", function () {
            GetCategories();
        });
    });

    function GetCategories() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCategories",
            data: '{searchTerm: "' + jQuery.trim($('[id*=txtCategory]').val()) + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var lstCategories = $("[id*=lstCategories]");
                lstCategories.empty();
                $.each(response.d, function () {
                    lstCategories.append($("<option></option>").val(this['Value']).html(this['Value']));
                });
            },
            failure: function (r) {
                alert(r.responseText);
            },
            error: function (r) {
                alert(r.responseText);
            }
        });
    }
</script>

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

[WebMethod]
public static List<ListItem> GetCategories(string searchTerm)
{
    List<ListItem> items = new List<ListItem>();
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT CategoryID,CategoryName FROM Categories WHERE CategoryName LIKE @Prefix + '%' OR @Prefix IS NULL";
    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand(query);
        cmd.Parameters.AddWithValue("@Prefix", !string.IsNullOrEmpty(searchTerm) ? searchTerm : (object)DBNull.Value);
        cmd.Connection = con;
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            items.Add(new ListItem
            {
                Value = sdr["CategoryID"].ToString(),
                Text = sdr["CategoryName"].ToString()
            });
        }
        con.Close();
    }

    return items;
}

VB.Net

<WebMethod>
Public Shared Function GetCategories(ByVal searchTerm As String) As List(Of ListItem)
    Dim items As List(Of ListItem) = New List(Of ListItem)()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT CategoryID,CategoryName FROM Categories WHERE CategoryName LIKE @Prefix + '%' OR @Prefix IS NULL"
    Using con As SqlConnection = New SqlConnection(conString)
        Dim cmd As SqlCommand = New SqlCommand(query)
        cmd.Parameters.AddWithValue("@Prefix", If(Not String.IsNullOrEmpty(searchTerm), searchTerm, CObj(DBNull.Value)))
        cmd.Connection = con
        con.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader()
        While sdr.Read()
            items.Add(New ListItem With {
                .Value = sdr("CategoryID").ToString(),
                .Text = sdr("CategoryName").ToString()
            })
        End While
        con.Close()
    End Using

    Return items
End Function

Screenshot