Hi SajidHussa,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<style type="text/css">
.highlight
{
background-color: #FFFFAF;
color: Red;
font-weight: bold;
}
</style>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js"></script>
<link rel="Stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$("[id$=txtSearch]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
} else {
response([{ label: 'No results found.', val: -1}]);
}
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
if (i.item.val == -1) {
$('[id$=txtSearch]').val("");
return false;
} else {
$("[id$=hfCustomerId]").val(i.item.val);
}
},
minLength: 1
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var regx = new RegExp('(' + this.term + ')', 'ig');
var label = item.value.replace(regx, "<span class='highlight'>" + this.term + "</span>");
return $("<li/>").data("ui-autocomplete-item", item).append($("<a>").html(label)).appendTo(ul);
};
});
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Services
Code
C#
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT ContactName, CustomerId FROM Customers WHERE ContactName LIKE @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
}
}
conn.Close();
}
}
return customers.ToArray();
}
protected void Submit(object sender, EventArgs e)
{
string customerName = Request.Form[txtSearch.UniqueID];
string customerId = Request.Form[hfCustomerId.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName + "\\nID: " + customerId + "');", true);
}
VB.Net
<WebMethod()> _
Public Shared Function GetCustomers(prefix As String) As String()
Dim customers As New List(Of String)()
Using conn As New SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT ContactName, CustomerId FROM Customers WHERE ContactName LIKE @SearchText + '%'"
cmd.Parameters.AddWithValue("@SearchText", prefix)
cmd.Connection = conn
conn.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
End While
End Using
conn.Close()
End Using
End Using
Return customers.ToArray()
End Function
Protected Sub Submit(sender As Object, e As EventArgs)
Dim customerName As String = Request.Form(txtSearch.UniqueID)
Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Name: " & customerName & "\nID: " & customerId & "');", True)
End Sub
Screenshot