Introduction

In this blog, we will discuss how to create autocomplete textbox in asp.net with the database using jQuery AJAX and web service.

Step-1

Create a database in SQL server of your choice as given below.

  1. USE [JQueryDB]
  2. GO
  3. SET ANSI_NULLS ON
  4. GO
  5. SET QUOTED_IDENTIFIER ON
  6. GO
  7. CREATE TABLE [dbo].[Country](
  8. [CountryID] [int] IDENTITY(1,1) NOT NULL,
  9. [CountryName] [nvarchar](100) NULL,
  10. CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED
  11. (
  12. [CountryID] ASC
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  14. ) ON [PRIMARY]
  15. GO
  16. SET ANSI_NULLS ON
  17. GO
  18. SET QUOTED_IDENTIFIER ON
  19. GO
  20. CREATE procedure [dbo].[spGetCountryName]
  21. @term varchar(50)
  22. as
  23. begin
  24. select CountryName
  25. from Country
  26. where CountryName like @term +'%'
  27. end
  28. GO

Step-2

Add database connection in a webconfig file of your project change data source and database as you created.

  1. <connectionStrings>
  2. <add name="DBCS" connectionString="data source=DESKTOP-K5N6EMF\SQLEXPRESS; database=JQueryDB;integrated security=SSPI" providerName="System.Data.SqlClient;"/>
  3. </connectionStrings>

Step-3

Add CountryService.asmx right click on project add new item and choose .asmx file. Write below code.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Services;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.Configuration;
  9. namespace AutoCompleteTextBox_Demo
  10. {
  11. /// <summary>
  12. /// Summary description for CountryService
  13. /// </summary>
  14. [WebService(Namespace = "http://tempuri.org/")]
  15. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  16. [System.ComponentModel.ToolboxItem(false)]
  17. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
  18. [System.Web.Script.Services.ScriptService]
  19. public class CountryService : System.Web.Services.WebService
  20. {
  21. [WebMethod]
  22. public List<string> GetCountryNames(string term)
  23. {
  24. List<string> listCountryName = new List<string>();
  25. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  26. using(SqlConnection con=new SqlConnection(CS))
  27. {
  28. SqlCommand cmd = new SqlCommand("spGetCountryName", con);
  29. cmd.CommandType = CommandType.StoredProcedure;
  30. SqlParameter parameter = new SqlParameter()
  31. {
  32. ParameterName = "@term",
  33. Value = term
  34. };
  35. cmd.Parameters.Add(parameter);
  36. con.Open();
  37. SqlDataReader rdr = cmd.ExecuteReader();
  38. while(rdr.Read())
  39. {
  40. listCountryName.Add(rdr["CountryName"].ToString());
  41. }
  42. return listCountryName;
  43. }
  44. }
  45. }
  46. }

Step-4

Add web form right click on project add new item and choose web form. Add script and styles cdn link in head section.

  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  2. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  3. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  4. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Step-5

Write below script to call CountryService.asmx

  1. <script type="text/javascript">
  2. $(document).ready(function () {
  3. $("#txtCountry").autocomplete({
  4. source: function (request, responce) {
  5. $.ajax({
  6. url: "CountryService.asmx/GetCountryNames",
  7. method: "post",
  8. contentType: "application/json;charset=utf-8",
  9. data: JSON.stringify({ term: request.term }),
  10. dataType: 'json',
  11. success: function (data) {
  12. responce(data.d);
  13. },
  14. error: function (err) {
  15. alert(err);
  16. }
  17. });
  18. }
  19. });
  20. });
  21. </script>

Step-6

Design HTML by grad and drop textbox control in web form.

  1. <div class="container">
  2. <h2>Autocomplete Texbox using JQuery Ajax with database in ASP.NET</h2>
  3. <label>Country Name</label>
  4. <asp:TextBox ID="txtCountry" CssClass="form-control col-md-3" runat="server"></asp:TextBox>
  5. </div>

Complete html code of web form.

  1. <!DOCTYPE html>
  2. <html>
  3. <head runat="server">
  4. <title>Autocomplete</title>
  5. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  6. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  7. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  8. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  9. <script type="text/javascript">
  10. $(document).ready(function () {
  11. $("#txtCountry").autocomplete({
  12. source: function (request, responce) {
  13. $.ajax({
  14. url: "CountryService.asmx/GetCountryNames",
  15. method: "post",
  16. contentType: "application/json;charset=utf-8",
  17. data: JSON.stringify({ term: request.term }),
  18. dataType: 'json',
  19. success: function (data) {
  20. responce(data.d);
  21. },
  22. error: function (err) {
  23. alert(err);
  24. }
  25. });
  26. }
  27. });
  28. });
  29. </script>
  30. </head>
  31. <body>
  32. <form id="form1" runat="server">
  33. <div class="container">
  34. <h2>Autocomplete Texbox using JQuery Ajax with database in ASP.NET</h2>
  35. <label>Country Name</label>
  36. <asp:TextBox ID="txtCountry" CssClass="form-control col-md-3" runat="server"></asp:TextBox>
  37. </div>
  38. </form>
  39. </body>
  40. </html>

Step-7 Run project ctr+F5

Final output

output