You can achieve this using the web service.
First of all, add the following code to your aspx page.
<div>
<input type="text" value="" id="tbCountries" />
</div>
Now create your web service using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.>WebService {
[WebMethod]
public List<string> ShowCountryList(string sLookUP)
{
List<string> lstCountries = new List<string>();
string sConnString = "Data Source=DNA;Persist Security Info=False;" +
"Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;";
SqlConnection myConn = new SqlConnection(sConnString);
SqlCommand objComm = new SqlCommand("SELECT CountryName FROM Country " +
"WHERE CountryName LIKE '%'+@LookUP+'%' ORDER BY CountryName", myConn);
myConn.Open();
objComm.Parameters.AddWithValue("@LookUP", sLookUP);
SqlDataReader reader = objComm.ExecuteReader();
while (reader.Read()) {
lstCountries.Add(reader["CountryName"].ToString());
}
myConn.Close(); return lstCountries;
}
}
Finally, create a jquery method to bind the text field to the webservice,
<script>
$(document).ready(function() {
BindControls();
});
function BindControls() {
$("#tbListOfCountries").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/ShowCountryList",
data: "{ 'sLookUP': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return { value: item }
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
}
</script>
source
share