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.
- <connectionStrings>
- <add name="conStr" connectionString="Database=Demo;data source=SQLEXPRESS; user id=sa;password=Abc123;" providerName="System.Data.SqlClient"/>
- </connectionStrings>
Step 3
Create the simple table named as Employee with EmpId, Name, and Address fields in SQL Server.
- CREATE TABLE [dbo].[Employee](
- [EmpId] [int] IDENTITY(1,1) Primary key NOT NULL ,
- [Name] [varchar](125) NULL,
- [Address] [varchar](125) NULL
- )
Step 4
Add Web Form
AutoCompleteTextBox.aspx.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="JQueryAutoCompleteTextBox.AutoCompleteTextBox" %>
-
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Auto Complete Textbox</title>
- <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
- <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
- <link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
- <script>
- $(document).ready(function () {
- $("#txtEmployee").autocomplete({
- source: function (request, response) {
- var param = { EmpName: $('#txtEmployee').val() };
- $.ajax({
- url: "AutoCompleteTextBox.aspx/getEmployees",
- data: JSON.stringify(param),
- dataType: "json",
- type: "POST",
- contentType: "application/json; charset=utf-8",
- dataFilter: function (data) { return data; },
- success: function (data) {
- console.log(JSON.stringify(data));
- response($.map(data.d, function (item) {
- return {
- value: item.EmpName +" ("+ item.Address+")"
- }
- }))
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- var err = eval("(" + XMLHttpRequest.responseText + ")");
- alert(err.Message)
-
- }
- });
- },
- minLength: 1
- });
- });
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table>
- <tr>
- <td>
- <asp:Label ID="lblEmployee" Text="Employee Search" runat="server"></asp:Label>
- </td>
- <td>
- <asp:TextBox ID="txtEmployee" runat="server" Width="200" placeholder="Employee Name"></asp:TextBox>
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Step 5
Write the code in the code behind file using [Webmethod], like this.
- using System;
- using System.Collections.Generic;
- using System.Web.Services;
- using System.Data.SqlClient;
- using System.Configuration;
-
- namespace JQueryAutoCompleteTextBox
- {
- public partial class AutoCompleteTextBox : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
-
- [WebMethod]
- public static List<Employees> getEmployees(string EmpName)
- {
- List<Employees> empObj = new List<Employees>();
- string cs = ConfigurationManager.ConnectionStrings["conStr"].ToString();
- try
- {
- using (SqlConnection con=new SqlConnection(cs))
- {
- using (SqlCommand com = new SqlCommand())
- {
- com.CommandText = string.Format( "select EmpId,Name,Address from employee where name like '{0}%'", EmpName);
- com.Connection = con;
- con.Open();
- SqlDataReader sdr = com.ExecuteReader();
- Employees emp = null;
- while (sdr.Read())
- {
- emp = new Employees();
- emp.EmpDbKey = Convert.ToInt32(sdr["EmpId"]);
- emp.EmpName = Convert.ToString(sdr["Name"]);
- emp.Address = Convert.ToString(sdr["Address"]);
- empObj.Add(emp);
- }
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error {0}",ex.Message);
- }
- return empObj;
- }
- }
- }
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.