Click here to Skip to main content
11,412,516 members (75,335 online)
Click here to Skip to main content

AutoComplete With DataBase and AjaxControlToolkit

, 8 Jul 2011 Ms-PL
Rate this:
Please Sign up or sign in to vote.
This is a very simple code which makes an Auto Complete Combo with database.
Sample Image - maximum width is 600 pixels

Introduction

This is very simple code which makes an Auto Complete Combo with database.

It's useful. First of all, you do not have to know about Ajax functions, just download the AJAX Control Toolkit on CodePlex and follow me, then enjoy. Besides when there are many rows, you can type part of the word in the text box, then it can offer all of the words which are similar to it.

Background: What is Ajaxcontroltoolkit?

The ASP.NET AJAX Control Toolkit is an open-source project built on top of the Microsoft ASP.NET AJAX framework and contains more than 30 controls that enable you to easily create rich, Interactive web pages. If you want to know more about it, visit this link.

Using the Code

It the first step, you must download AjaxControlToolkit from here for .NET 3.5 OR here for .NET 4.0.

You must go here and download ajaxcontroltoolkit, then Copy ajaxcontroltoolkit and paste them to Bin Folder, right click on solution, choose Add Reference, in the browse tab double click on the Bin Folder, and double click on ajaxcontroltoolkit, then on the Build Menu > click Rebuild.

DataBase

New Query

CREATE TABLE [dbo].[tblCustomer](
	    [CompanyName] [nvarchar](500) NULL,
	    [ID] [int] IDENTITY(1,1) NOT NULL
        ) ON [PRIMARY]

insert into dbo.tblCustomer(CompanyName) values('calemard')
insert into dbo.tblCustomer(CompanyName) values('dantherm')
insert into dbo.tblCustomer(CompanyName) values('dango dienenthal')
insert into dbo.tblCustomer(CompanyName) values('daewoo')
insert into dbo.tblCustomer(CompanyName) values('daim engineering')

Visual Studio 2008 - .NET 3.5: Create Web Site and name it AutoComplete, create Web Form and name it AutoComplete.aspx, in HTML view, write this code.
But there is a little difference between C# and VB in this section.

  1. This code in the bottom is for C# coders.
  2. If you are a VB coder, please modify 2 sections in page tag
    1. One: correct language=VB
    2. Two: correct CodeFile="AutoComplete.aspx.vb"
<%@ Page Language="C#" AutoEventWireup="false"
         CodeFile="AutoComplete.aspx.cs" Inherits="AutoComplete" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
         TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager  ID="ScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:AutoCompleteExtender ID="autoComplete1" runat="server"
  EnableCaching="true"
  BehaviorID="AutoCompleteEx"
  MinimumPrefixLength="2"
  TargetControlID="myTextBox"
  ServicePath="AutoComplete.asmx"
  ServiceMethod="GetCompletionList" 
  CompletionInterval="1000"  
  CompletionSetCount="20"
  CompletionListCssClass="autocomplete_completionListElement"
  CompletionListItemCssClass="autocomplete_listItem"
  CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
  DelimiterCharacters=";, :"
  ShowOnlyCurrentWordInCompletionListItem="true">
  <Animations>
  <OnShow>
  <Sequence>
  <%-- Make the completion list transparent and then show it --%>
  <OpacityAction Opacity="0" />
  <HideAction Visible="true" />

  <%--Cache the original size of the completion list the first time
    the animation is played and then set it to zero --%>
  <ScriptAction Script="// Cache the size and setup the initial size
                                var behavior = $find('AutoCompleteEx');
                                if (!behavior._height) {
                                    var target = behavior.get_completionList();
                                    behavior._height = target.offsetHeight - 2;
                                    target.style.height = '0px';
                                }" />
  <%-- Expand from 0px to the appropriate size while fading in --%>
  <Parallel Duration=".4">
  <FadeIn />
  <Length PropertyKey="height" StartValue="0" 
	EndValueScript="$find('AutoCompleteEx')._height" />
  </Parallel>
  </Sequence>
  </OnShow>
  <OnHide>
  <%-- Collapse down to 0px and fade out --%>
  <Parallel Duration=".4">
  <FadeOut />
  <Length PropertyKey="height" StartValueScript=
	"$find('AutoCompleteEx')._height" EndValue="0" />
  </Parallel>
  </OnHide>
  </Animations>
  </ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="myTextBox" autocomplete ="off" runat="server"></asp:TextBox>

</form>
</body>
</html>

For StyleSheet (CSS file)

  • Create StyleSheet: Solution > Right Click > Add New Item > Web Service >
  • Name: StyleSheet.css
  • Language: Visual Basic OR C#
  • Go To > StyleSheet.css (File) > Ctrl+A (Select All) > Delete
  • Go to this section (below) > Select this code > Ctrl+C >
  • Go To StyleSheet.css (file) > Ctrl+V (paste)
/*AutoComplete flyout */
.autocomplete_completionListElement
{
    margin : 0px!important ;
    background-color : inherit ;
    color : windowtext ;
    border : buttonshadow ;
    border-width : 1px ;
    border-style : solid ;
    cursor : 'default' ;
    overflow : auto ;
    height : 200px ;
    font-family : Tahoma ;
    font-size : small ;
    text-align : left ;
    list-style-type : none ;
    }
/* AutoComplete highlighted item */
.autocomplete_highlightedListItem
   {
    background-color : #ffff99 ;
    color : black ;
    padding : 1px ;
    }

    /* AutoComplete item */
.autocomplete_listItem
    {
    background-color : window ;
    color : windowtext ;
    padding : 1px ;
   }

For VB

  • Create Web Service: Solution > Right Click > Add New Item > Web Service >
  • Name: AutoComplete.asmx
  • Language: Visual Basic
  • Go To > App_Code > AutoComplete.vb
' (c) Copyright Microsoft Corporation.
' This source is subject to the Microsoft Public License.
' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
' All other rights reserved.
Imports System
Imports System.Collections
Imports System.Linq
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Linq
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, 
' uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AutoComplete
    Inherits System.Web.Services.WebService
    Dim cn As New SqlClient.SqlConnection()
    Dim ds As New DataSet
    Dim dt As New DataTable
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, _
	ByVal count As Integer) As String()

        'ADO.Net
        Dim strCn As String = _
		"data source=.;Initial Catalog=MyDB;Integrated Security=True"
        cn.ConnectionString = strCn
        Dim cmd As New SqlClient.SqlCommand
        cmd.Connection = cn
        cmd.CommandType = CommandType.Text
        'Compare String From Textbox(prefixText) 
        'AND String From Column in DataBase(CompanyName)
        'If String from DataBase is equal to String from TextBox(prefixText) 
        'then add it to return ItemList
        '-----I defined a parameter instead of passing value 
        'directly to prevent SQL injection--------'
        cmd.CommandText = "select * from tblCustomer Where CompanyName like @myParameter"
        cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%")

        Try
            cn.Open()
            cmd.ExecuteNonQuery()
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(ds)
        Catch ex As Exception
        Finally
            cn.Close()
        End Try

        dt = ds.Tables(0)

        'Then return List of string(txtItems) as result

        Dim txtItems As New List(Of String)
        Dim dbValues As String

        For Each row As DataRow In dt.Rows

            ''String From DataBase(dbValues)
            dbValues = row("CompanyName").ToString()
            dbValues = dbValues.ToLower()
            txtItems.Add(dbValues)

        Next

        Return txtItems.ToArray()

    End Function

End Class

For C#

  • Web Service: Solution > Right Click > Add New Item > Web Service >
  • Name: AutoComplete.asmx
  • Language: C#
  • Go To > App_Code > AutoComplete.cs
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

///<summary>
/// Summary description for AutoComplete
///</summary>

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, 
// uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        //ADO.Net
        SqlConnection cn =new SqlConnection();
        DataSet ds = new DataSet();
        DataTable  dt = new DataTable();
        String strCn = "data source=.;Initial Catalog=MyDB;Integrated Security=True";
        cn.ConnectionString = strCn;
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        //Compare String From Textbox(prefixText) AND String From 
        //Column in DataBase(CompanyName)
        //If String from DataBase is equal to String from TextBox(prefixText) 
        //then add it to return ItemList
        //-----I defined a parameter instead of passing value directly to 
        //prevent SQL injection--------//
        cmd.CommandText = "select * from tblCustomer Where CompanyName like @myParameter";
        cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");

        try
        {
            cn.Open();
            cmd.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
        }
        catch
        {
        }
        finally
        {
            cn.Close();
        }
        dt = ds.Tables[0];

	    //Then return List of string(txtItems) as result
        List<string> txtItems =new List<string>();
        String  dbValues;

        foreach (DataRow row  in dt.Rows)
        {
             //String From DataBase(dbValues)
            dbValues = row["CompanyName"].ToString();
            dbValues = dbValues.ToLower();
            txtItems.Add(dbValues);
        }

        return txtItems.ToArray();
    }
}

Summary

GetCompletionList is a function that catches 2 arguments, prefixText as string and count as int.

When you type some characters, they are saved in prefixText and number of your characters are saved in count. And at the end, function returns list of string (they are similar to your characters) which has been obtained as follows:

I have written some code in ADO.NET section, these rows have been filtered by prefixText, which are similar to your characters that are typed in text box.
Additionally, I defined a parameter instead of passing value directly to prevent SQL injection.

I create txtItems in List of string data type, we can save words that we want. Then in a foreach loop, I converted them into tolower,  I added those values to my result value (txtItems), finally I return txtItems.

Try Step by Step

  1. Go here for .NET 3.5 OR here for .NET 4.0 and download the AjaxControlToolkit file.
  2. Copy the folder "AjaxControlToolkit.Dll" and all dependers, there are 18 objects, to your web site Bin folder (C:\AutoComplete\Bin).
  3. Right click on solution, choose refresh, then right click again and click add reference, then in the browse tab double click on the Bin Folder, and double click on ajaxcontroltoolkit, on the Build Menu > click Rebuild.
  4. Create database and tables like above, and add some rows which have common words.
  5. Create Web Form and name it: "AutoComplete.aspx". In the HTML view, write some code like above. (This should be exactly like my code because this section is case sensitive).
  6. Create a webservice:
    Solution > Right Click > Add New Item > Web Service > Name: AutoComplete.asmx Language: C# or VB
    Go To > App_Code > AutoComplete.cs
  7. For some animation effect, I added Stylesheet, use it for user friendly.
  8. If you are a VB coder, use the VB sample, otherwise use the C# sample.
  9. Run the program and write in Text Box a word that contains 2 characters or more such as da, and you will see a list of words that are similar to your character.

Feedback

Feel free to leave any feedback on this article; it is a pleasure to see your comments and vote about this code. If you have any questions, please do not hesitate to ask me here.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Mahsa Hassankashi
Software Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
I have been working with .Net framework for 10 years.
I`d like to challenge with complex problem, then make it easy for using everyone. This is the best joy.

ICT Master
Founder at technical.cosmicverse.info (Free Web Tutorial)
-------------------------------------------------------------
Diamond is nothing except the pieces of the coal which have continued their activities finally they have become Diamond.

*Article of The Community Spotlight in Microsoft ASP.NET, Wednesday, February 11, 2015, www.asp.net
*Article of The Day in Microsoft ASP.NET Tuesday, February 3, 2015, www.asp.net/community/articles
*1 Jan 2015: CodeProject MVP 2015
*22 Mar 2014: Best Web Dev Article of February 2014 - Second Prize

http://www.cosmicverse.info/
http://www.technical.cosmicverse.info
Follow on   Google+   LinkedIn

Comments and Discussions

 
GeneralCongrats Pin
Gaurav Kumar Arora at 12-Apr-15 22:41
professionalGaurav Kumar Arora12-Apr-15 22:41 
GeneralRe: Congrats Pin
Mahsa Hassankashi at 18-Apr-15 3:06
mvpMahsa Hassankashi18-Apr-15 3:06 
GeneralRe: Congrats Pin
Gaurav Kumar Arora at 18-Apr-15 12:03
professionalGaurav Kumar Arora18-Apr-15 12:03 
QuestionArticles Of The Day Pin
Sibeesh Passion at 10-Apr-15 21:59
professionalSibeesh Passion10-Apr-15 21:59 
AnswerRe: Articles Of The Day Pin
Mahsa Hassankashi at 18-Apr-15 3:06
mvpMahsa Hassankashi18-Apr-15 3:06 
GeneralRe: Articles Of The Day Pin
Sibeesh Passion at 18-Apr-15 22:50
professionalSibeesh Passion18-Apr-15 22:50 
GeneralMy vote of 5 Pin
Dariush Tasdighi at 8-Apr-15 21:34
memberDariush Tasdighi8-Apr-15 21:34 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi at 18-Apr-15 3:07
mvpMahsa Hassankashi18-Apr-15 3:07 
Questionmultiple autocomplete Pin
Member 11512987 at 10-Mar-15 5:09
memberMember 1151298710-Mar-15 5:09 
AnswerRe: multiple autocomplete Pin
Member 11482392 at 11-Mar-15 7:06
memberMember 1148239211-Mar-15 7:06 
GeneralRe: multiple autocomplete Pin
OriginalGriff at 11-Mar-15 7:09
protectorOriginalGriff11-Mar-15 7:09 
QuestionHow to add multiple method in autocomplete.cs ? Pin
Shahnawazcode at 25-Feb-15 19:42
memberShahnawazcode25-Feb-15 19:42 
AnswerRe: How to add multiple method in autocomplete.cs ? Pin
Mahsa Hassankashi at 18-Apr-15 3:01
mvpMahsa Hassankashi18-Apr-15 3:01 
GeneralMy vote of 5 Pin
Sibeesh|Passion at 15-Feb-15 4:59
professionalSibeesh|Passion15-Feb-15 4:59 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi at 15-Feb-15 6:46
mvpMahsa Hassankashi15-Feb-15 6:46 
GeneralRe: My vote of 5 Pin
Sibeesh|Passion at 15-Feb-15 18:37
professionalSibeesh|Passion15-Feb-15 18:37 
QuestionI have a string variable like string A = "Name:venkat,PhNo:77089,City:Test" i want to get venkat and 77089 and Test values then store it separate variable using c# I want simple code how to get it. Thanks & Regards, venkat Pin
venkat167 at 22-Jan-15 2:36
membervenkat16722-Jan-15 2:36 
AnswerRe: I have a string variable like string A = "Name:venkat,PhNo:77089,City:Test" i want to get venkat and 77089 and Test values then store it separate variable using c# I want simple code how to get it. Thanks & Regards, venkat Pin
Mahsa Hassankashi at 22-Jan-15 14:18
mvpMahsa Hassankashi22-Jan-15 14:18 
QuestionThis works in Dev but not in Production Pin
Member 7921459 at 27-Dec-14 12:15
memberMember 792145927-Dec-14 12:15 
AnswerRe: This works in Dev but not in Production Pin
Mahsa Hassankashi at 30-Dec-14 14:20
memberMahsa Hassankashi30-Dec-14 14:20 
GeneralMy vote of 5 Pin
Sibeesh KV at 18-Nov-14 23:49
professionalSibeesh KV18-Nov-14 23:49 
Questionnot worked Pin
Member 10502632 at 6-Nov-14 21:43
memberMember 105026326-Nov-14 21:43 
AnswerRe: not worked Pin
Mahsa Hassankashi at 7-Nov-14 1:16
memberMahsa Hassankashi7-Nov-14 1:16 
GeneralRe: not worked Pin
Member 10502632 at 7-Nov-14 4:07
memberMember 105026327-Nov-14 4:07 
QuestionUn Comment ScriptService Pin
Member 11026721 at 26-Aug-14 21:25
memberMember 1102672126-Aug-14 21:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150427.1 | Last Updated 8 Jul 2011
Article Copyright 2011 by Mahsa Hassankashi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid