Auto Complete TextBox Using ASP.NET jQuery AJAX call

 
 
There are so many ways to create AutoComplete textbox in ASP.NET using AJAX call but here, I'm using jQuery.
Before you start your project, download the jQuery file from - https://jquery.com/download/

After downloading, follow the below-mentioned few steps.

Step 1

Create one ASP.NET Project.

Step 2

Add Connection String in web config file in your project.
  1. <connectionStrings>  
  2.    <add name="conStr" connectionString="Database=Demo;data source=SQLEXPRESS; user id=sa;password=Abc123;" providerName="System.Data.SqlClient"/>  
  3.  </connectionStrings>  
Step 3

Create the simple table named as Employee with EmpId, Name, and Address fields in SQL Server.
  1. CREATE TABLE [dbo].[Employee](  
  2.     [EmpId] [int] IDENTITY(1,1) Primary key NOT NULL ,  
  3.     [Name] [varchar](125) NULL,  
  4.     [Address] [varchar](125) NULL   
  5. )  
 Step 4

Add Web Form AutoCompleteTextBox.aspx.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="JQueryAutoCompleteTextBox.AutoCompleteTextBox" %>  
  2.   
  3. <!DOCTYPE html>  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title>Auto Complete Textbox</title>  
  7.      <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>    
  8.     <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>    
  9.     <link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />  
  10.      <script>  
  11.          $(document).ready(function () {  
  12.              $("#txtEmployee").autocomplete({  
  13.                  source: function (request, response) {  
  14.                      var param = { EmpName: $('#txtEmployee').val() };  
  15.                      $.ajax({  
  16.                          url: "AutoCompleteTextBox.aspx/getEmployees",  
  17.                          data: JSON.stringify(param),  
  18.                          dataType: "json",  
  19.                          type: "POST",  
  20.                          contentType: "application/json; charset=utf-8",  
  21.                          dataFilter: function (data) { return data; },  
  22.                          success: function (data) {  
  23.                              console.log(JSON.stringify(data));  
  24.                              response($.map(data.d, function (item) {  
  25.                                  return {  
  26.                                      value: item.EmpName +" ("+ item.Address+")"  
  27.                                  }  
  28.                              }))  
  29.                          },  
  30.                          error: function (XMLHttpRequest, textStatus, errorThrown) {  
  31.                              var err = eval("(" + XMLHttpRequest.responseText + ")");  
  32.                              alert(err.Message)  
  33.                              // console.log("Ajax Error!");    
  34.                          }  
  35.                      });  
  36.                  },  
  37.                  minLength: 1 //This is the Char length of inputTextBox    
  38.              });  
  39.          });  
  40.     </script>  
  41. </head>  
  42. <body>  
  43.     <form id="form1" runat="server">  
  44.         <div>  
  45.             <table>  
  46.                 <tr>  
  47.                     <td>  
  48.                         <asp:Label ID="lblEmployee" Text="Employee Search" runat="server"></asp:Label>  
  49.                     </td>  
  50.                     <td>  
  51.                         <asp:TextBox ID="txtEmployee" runat="server" Width="200" placeholder="Employee Name"></asp:TextBox>  
  52.                     </td>  
  53.                 </tr>  
  54.             </table>  
  55.         </div>  
  56.     </form>  
  57. </body>  
  58. </html>  
Step 5

Write the code in the code behind file using [Webmethod], like this.
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web.Services;  
  4. using System.Data.SqlClient;  
  5. using System.Configuration;  
  6.   
  7. namespace JQueryAutoCompleteTextBox  
  8. {  
  9.     public partial class AutoCompleteTextBox : System.Web.UI.Page  
  10.     {  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.         }  
  14.   
  15.         [WebMethod]  
  16.         public static List<Employees> getEmployees(string EmpName)  
  17.         {  
  18.             List<Employees> empObj = new List<Employees>();  
  19.             string cs = ConfigurationManager.ConnectionStrings["conStr"].ToString();  
  20.             try  
  21.             {  
  22.                 using (SqlConnection con=new SqlConnection(cs))  
  23.                 {  
  24.                     using (SqlCommand com = new SqlCommand())  
  25.                     {  
  26.                         com.CommandText = string.Format( "select EmpId,Name,Address from employee where name like '{0}%'", EmpName);  
  27.                         com.Connection = con;                          
  28.                         con.Open();  
  29.                         SqlDataReader sdr = com.ExecuteReader();  
  30.                         Employees emp = null;  
  31.                         while (sdr.Read())  
  32.                         {  
  33.                              emp = new Employees();  
  34.                             emp.EmpDbKey = Convert.ToInt32(sdr["EmpId"]);  
  35.                             emp.EmpName = Convert.ToString(sdr["Name"]);  
  36.                             emp.Address = Convert.ToString(sdr["Address"]);  
  37.                             empObj.Add(emp);  
  38.                         }  
  39.                     }  
  40.                 }  
  41.             }  
  42.             catch (Exception ex)  
  43.             {  
  44.                 Console.WriteLine("Error {0}",ex.Message);  
  45.             }  
  46.             return empObj;  
  47.         }  
  48.     }  
  49. }  
Summary

This article showed how to use a jQuery UI AutoComplete in ASP.NET using jQuery with a complex object. Let me know if you have a better approach for this. I'm waiting for your comments.
Ebook Download
View all
Learn
View all