Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Jquery autocomplete textbox with multiple words separated by comma or semicolon in asp.net

Jul 3, 2012
Introduction:

In this article I will explain how to implement JQuery UI autocomplete textbox with multiple words or values with comma separated or semi colon separated in asp.net.
Description:

In previous articles I explained JQuery autocomplete textbox with asp.net and
JQuery autocomplete textbox with images in asp.net and many articles relating to JQuery. Now I will explain how to implement autocomplete textbox with multiple word selection in asp.net.
To implement this concept first we need to design table in database to save user details in database.

Column Name
Data Type
Allow Nulls
UserId
int(set identity property=true)
No
UserName
varchar(50)
Yes
Location
nvarchar(max)
Yes
After completion table design enter some of user details in database to work for our sample.
Write the following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtSearch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txtSearch").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" Width="300px"></asp:TextBox>
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script and css files by using those files we have a chance to implement autocomplete textbox with multiple values selection in asp.net. To get those files download attached folder and add the urls mentioned in header section to your application

Another thing here we need to know is script functions in header section

$("#txtSearch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
This is the function declaration of JSON format we are using this JSON function to call web methods using JQuery $.ajax() whenever we need to make Ajax call with JQuery then we will use JSON functions like as we mentioned in above format. If you want to know more about it check these posts call pagemethods with JSON and autocomplete textbox with Jquery.

Now open code behind file and add following namespaces


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
After that write the following code

C#.NET Code

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]

public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
VB.NET Code:


Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Web.Services

Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

End Sub

<WebMethod()> _
Public Shared Function GetAutoCompleteData(ByVal username As String) As List(Of String)
Dim result As New List(Of String)()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'+@SearchText+'%'", con)
con.Open()
cmd.Parameters.AddWithValue("@SearchText", username)
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
result.Add(dr("UserName").ToString())
End While
Return result
End Using
End Using
End Function
End Class
Now run your application and check the output that would be like this   

Download sample code attached


  

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

45 comments :

Alok Kumar Sharma said...
This comment has been removed by the author.
Alok Kumar Sharma said...

Dear Friend,

I have created a web service and hosted on the server like http://119.82.71.78:903/MessageBoardService.asmx
and i called it on another project but i am not able to access this web sevrice . what could be the reason ?
MessageBoardService.asmx.cs

//Code

using System;
using System.Collections;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.Script.Services;

///
/// Summary description for MessageBoardService
///
[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 MessageBoardService : System.Web.Services.WebService
{

public MessageBoardService()
{

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


[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List GetAutoCompleteData(string username)
{
List result = new List();
if (!string.IsNullOrEmpty(username))
{
using (SqlConnection con = new SqlConnection("Data Source=MySerevr;Max Pool Size=600; Initial Catalog=MyMBDB;Persist Security Info=True;User ID=sa;Password=saa"))
{

using (SqlCommand cmd = new SqlCommand("select MemberFullName+'<'+UserID+'>' As username from View_MemberInformation where MemberFullName LIKE'%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
//return result;
}
}
}
return result;
}
}
and in aspx page // This is another projects.





$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://119.82.71.78:903/MessageBoardService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
alert(result.status)
}
});
}
});
}

But its working fine where webservice is hosted.

Thanks
Alok Kumar sharma
alokmca1984@gmail.com
India

Anonymous said...

dfgadgaa

Milind said...

Hi Suresh,

Thanks for sharing this article.

There is an error in sample code(default.aspx).

The below url is not working for sample code.
url: "Default.aspx/GetAutoCompleteData",

The url should be
url: "AutoCompletewithMultipleSelection.aspx/GetAutoCompleteData",

Suresh Dasari said...

@Milind,
There is no error in code Default.aspx is the page name of my application if you use another pagename then you need to change url: "PageName/MethodName"

Milind said...

There is an error in downloaded code.

The page name of application is AutoCompletewithMultipleSelection.aspx.

code :
url: "Default.aspx/GetAutoCompleteData",

Suresh Dasari said...

@Milind,
that is not problem or error in post. Please give your application pagename that's enough

Milind said...

there is no error on the article.

there is problem on downloadable sample code.

Suresh Dasari said...

Thanks Milind...

i updated downloadable sample also...

Milind said...

No problem. :-)

Anonymous said...

nice but i mnot able to use it on my master page :(
any solution?

Anonymous said...

its working perfectly on simple / single page
but on the page where master page is included i m not able to use it.
plz give me solution for tat with full code thanks for great article

Suresh Dasari said...

it will work on master pages also i hope you guys are not adding the jquery refrences in master that's the reason that auto complete not working in master. Please check it once...

Ankur Jain said...

If we want autocomplete search for two textboxes in the same aspx page, which will fetch data from two different tables. Then what will be the code for that?

Anonymous said...

Hi Suresh

Thanks, this is great and works perfectly and easily. However have you explored formating the input so that it is formatted as a label e.g as the example on this page textextjs dot com/?

Anonymous said...

Re: 13
it does not work on a child page of a master page. all the references are correct and also the url to the web service, case of json etc... i am using eact same code on a page that is not a child page of master page and it works... any ideas? thanks.

Anonymous said...

Re: 13 and 16

It does work on child page of master page however reference the client id of the textbox i.e "#<%=txtSearch.ClientID%>"

AbhiTheFlame said...

Awesome

Ankur Dalal said...

Hi Suresh,
Nice work! I need when you select "Mahendra" so it would not be next time in List of search.
Can you help me into this.
Thanks in advance.
Great thanks again.

- Ankur Dalal

Srinivas Shahukaru said...

Suresh, Naku koncham JQuery and Javascript help kavali ..some thing related to Autocomplete and JS Keydown event ... requirement chala typical vundi..asalu logic idea ne ravatam ledu...ma native kuda tenali ne...pls help me..ne contact number cheppu ...my contact is 8861319319

Anonymous said...

I using jquery tokeninput, i want you give me example ASP.NET server-side script for generating
responses suitable for use with jquery-tokeninput

Thanks!!!

Saidi Reddy said...

Hi Suresh. Thank you for Sharing this . i have a query in my ASpx page am having two Auto Complete textboxes . how can i fire only one event at a time.

shamseena.kn said...

It is so great article and easily understandable...I am new to Jquery.So I need one more thing suresh..How to get all the UserId of the all selected Username??I saw one of your article to select one item and its id.In this case how can I get multiple ids.Can you help me into this.
Thanks in advance.
Thanks again.

Arun Kumar said...

Hi, i checked this. is it working in user Control ?
can u tell me please

Hazarath Dudekula said...

Suresh ,
after deploying in IIS
SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
will works perfectly
but
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

won't work , it will give an alert with "error".
Is there any thing like we have to hard code this connection string in code file .
please check and leave a reply

Thanks
However nice implementation

jaydee777 said...

Works fine. Thanks
just one correction: this
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); }
with this.
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) { event.preventDefault(); }

Anonymous said...

there is multiple spaces in between last charecter of name and comma (,), how to avoid it?

Anonymous said...

Nice Article suresh
But when adding masterpage its not working

sandy said...

innstead of this "#txtSearch" use client id

"#<%=txtSearch.ClientID%>". it will work for master pages also

Anonymous said...

hello,
i write this method in webservice service.asmx

and replaced code sevice.asmx/methodname
but that autosuggestion is not working

Joe said...

hello,
I would like to ask how to delete the item that is selected
Thanks a lot.

BR

Gaurav Bhardwaj said...

Sir I want to remove comma (,) between two words in textbox ,How can i do that??

Anonymous said...

im not getting the CSS link in the internet.. may be you have given wrong css link..please give me correct css link.

vikram samal said...

Hell Sir,I am trying to use this useful stuff in my application,where I have to select Country & State from Dropdownlist,and after selecting the State I am trying to pick cities ,,Which it should come out In this Format,,
The Thing i need to mention is I need to pass another Parameter in that 'GetAutoCompleteData' List
Now You just tell me hpw to pass another Parameter and how to retreve it In Source Page .

Pradeep K. Rajyaguru said...

Sir i am use your code. Can you help me in retrieving the all the values selected by the user. I only get first value.

Anonymous said...

"#<%=txtSearch.ClientID%>". I am trying to add that id in master page..but it is not woking while use master page....

Anonymous said...

Hi,
How can i give style to the username i have selected in textbox?? For example: i type su in search boz and suresh from the populated list. now i want to apply style to the "suresh" record how is this possible.


Sagar Raykar said...
This comment has been removed by the author.
Sagar Raykar said...
This comment has been removed by the author.
Sagar Raykar said...

it didn't work for me , it gives error when i type single letter ,
i want do that search after 3 letter
please help

Anonymous said...

what is keydown

Anonymous said...

for the master page write this code in page_load. its work....
ScriptManager.RegisterStartupScript(
this, this.GetType(), "ctl00_ContentPlaceHolder1_txtkeyword", "SearchText1()", true);

Ali Özcan said...

Hi friend!
Thank you very much for the article. Worked for me too :)

Melvin said...

working.... but its affecting other pages




the above line in webconfig file is disabling my session variables. please help.

Mohsin Azam said...

you are using this in ajax
data: "{'username':'" + extractLast(request.term) + "'}",
but i am using
data: { term: request.term },
error occur plz guide me

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.