Saturday, 21 June 2014

Autocomplete Textbox in Asp.Net With DataBase Using C# AjaxControlToolkit

6/21/2014 - By Pranav Singh 26

In this article I will show you how you can create an auto complete text box using ajaxcontroltoolkit AutoCompleteExtender in your asp.net application using c#.Net and VB.net.


Now for this article first we will download ajaxcontroltoolkit. Now we will add into our visual studio. I have already show you How to Use and Install Ajaxcontroltoolkit in Asp.Net, So refer this article.

Now for this article first we will add the .aspx page, and add the below html tag.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextboxInAjaxToolkit.aspx.cs"
    Inherits="ProjectDemo_Asp.et.AutoCompleteTextboxInAjaxToolkit" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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 Textbox in Asp.Net With DataBase Using C# AjaxControlToolkit
    </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        Search : <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       
        <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
                    ServiceMethod="AutoCompleteAjaxRequest"
                    ServicePath="AutoComplete.asmx"
                    MinimumPrefixLength="2"
                    CompletionInterval="100"
                    EnableCaching="false"
                    CompletionSetCount="10"
                    TargetControlID="TextBox1" 
                    FirstRowSelected="false">
        </asp:AutoCompleteExtender>
    </div>
    </form>
</body>
</html>

In above code you can see that I have specified the TargetControlID="TextBox1" . This tag will used for specifying that in which control auto suggest will appear.

Now we will see hw to receive data from data base. For this in our AutoCompleteExtender tag we have two properties ServiceMethod and ServicePath . In this we will define web service name and method . For this add a webservice file in your project (.asmx). So here is the code of you webservice.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.OleDb;

namespace ProjectDemo_Asp.et
{
    /// <summary>
    /// Summary description for AutoComplete
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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
    {

        [WebMethod]
        public string[] AutoCompleteAjaxRequest(string prefixText, int count)
        {
            List<string> ajaxDataCollection = new List<string>();
            DataTable _objdt = new DataTable();
            _objdt = GetDataFromDataBase(prefixText);
                if(_objdt.Rows.Count>0)
                {
                    for (int i = 0; i < _objdt.Rows.Count; i++)
                    {
                        ajaxDataCollection.Add(_objdt.Rows[i]["LanguageName"].ToString());
                    }
                }
            return ajaxDataCollection.ToArray();
        }
        /// <summary>
        /// Function for retriving data from database
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataFromDataBase(string prefixText)
        {
            string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\bookstore.mdb;Persist Security Info=False;";
            DataTable _objdt = new DataTable();
            string querystring = "select * from ProLanguage where LanguageName like '%" + prefixText + "%';";
            OleDbConnection _objcon = new OleDbConnection(connectionstring);
            OleDbDataAdapter _objda = new OleDbDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            return _objdt;
        }
    }
}

In above code I have used access database, you can use the sql and other database.

Note: When you create  a webservice your [System.Web.Script.Services.ScriptService] attribute will be commented . So uncomment this otherwise you AutoCompleteExtender will not be able to access the webservice method.

Now run the page and check the output.


About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

26 comments:

  1. All done as you suggested but not working....

    ReplyDelete
  2. Now it is working correctly . I found problem in creating asmx file. Thanks for this nice coding .

    ReplyDelete
    Replies
    1. Hi Manmohan,
      Thanks for your valuable comment. keep visiting.

      Delete
  3. Its working fine. Nice post and helpfull for all. thaks

    ReplyDelete
    Replies
    1. Thanks for valuable comment. keep visiting.

      Delete
  4. System.Web.Script.Services.ScriptService is not Please help me

    ReplyDelete
    Replies
    1. Hi please check the webservice which you are using in your application. have a look of the below links for solution.

      http://stackoverflow.com/questions/7406485/how-to-solve-only-web-services-with-a-scriptservice-attribute-on-the-class-def

      http://stackoverflow.com/questions/3053181/cannot-find-system-web-script-service-namespace-error-after-upgrading-to-visual

      http://www.codeproject.com/Articles/521723/Web-Service-and-Script-Service

      Delete
  5. If the example is not working, check if you have uncomment the following line in the webservice:

    [System.Web.Script.Services.ScriptService]

    ReplyDelete
    Replies
    1. First thing example is perfectly working.
      I did not understand your problem. please clear it.

      Delete
  6. Could not load file or assembly 'AjaxControlToolKit' or one of its dependencies. The system cannot find the file specified.

    I got Above error if i include
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

    and if i did not include above line then AutoCompleteExtender is giving error. I am using MSVS2013. Can you help? Thanks in advance

    ReplyDelete
    Replies
    1. Please check weather you have installed the latest version of AjaxControlToolkit or not

      Delete
    2. Yes I downloaded "ASP.NET AJAX Control Toolkit v15.1.4" which is latest. Its an EXE and it installs its own component.. Which doesn't work... :( So downloaded the zips of AjaxControlToolKit DLLs Dec 2013 release which is latest DLL again.. And got the same :(

      Delete
    3. Using this one "ASP.NET AJAX Control Toolkit v15.1.4" and changed asp:AutoCompleteExtender to ajaxToolkit:AutoCompleteExtender...

      Yupee! it works... Thanks a lot man for your blog and coments :)

      Delete
    4. Hi,
      Tried to write a click event on searched items using OnClientItemSelected". Tried click events in .cs file and also by JavaScript but the final result is it stopped searching. Should I have to write click event listener in the web service class, or somthing else. Can you help.
      Thanks.

      Delete
  7. Hola amigo disculpa pero no me funciono tu codigo me podrias ayudar

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Thanks Brother...working fine

    ReplyDelete
  10. MicrosoftAjax.js:6 Uncaught TypeError: Cannot read properties of undefined (reading 'webServiceFailedNoMsg')
    at Array.x (MicrosoftAjax.js:6:97920)
    at MicrosoftAjax.js:6:51370
    at Sys.Net.WebRequest.completed (MicrosoftAjax.js:6:89678)
    at XMLHttpRequest._onReadyStateChange (MicrosoftAjax.js:6:84277)

    error on this

    ReplyDelete
    Replies
    1. You must have some issue with your web method. Please check with the ajaxcontroltoolkit dll version also.

      Delete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top