Auto Complete with Database in Asp.net Using Jquery
First add a Asp.net website and name as AutoCompleteDB
Now add a Default.aspx page and name it as AutoComplete
Now create database in SQL SERVER :
Autocomplete.aspx code :
%@ Page Language="C#" AutoEventWireup="true" CodeFile="AUTOCOMPLETE.aspx.cs" Inherits="AUTOCOMPLETE" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" 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 id="Head1" runat="server">
<title>Database AutoComplete Using JQuery</title>
<link href="cs/Style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.3.js" type="text/javascript" language="javascript"></script>
<script src="js/jquery-ui.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript" language="javascript">
function Load()
{
var ds=null;
ds = <%=lists %>;
$( "#txtCountry" ).autocomplete({
source: ds
});
}
</script>
</head>
<body onload="Load()">
<form id="form1" runat="server">
<h3>
Autocomplete using jquery</h3>
<div class="ui-widget">
<label for="tags">
Country :
</label>
<input id="txtCountry" />
</div>
</form>
</body>
</html>
AutoComplete.cs file :
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Data.SqlClient;
public partial class autocompleteusingjquery : System.Web.UI.Page
{
SqlConnection conn = null;
public string lists = null;
protected void Page_Load(object sender, EventArgs e)
{
lists = null;
lists = BindName();
}
private string BindName()
{
DataTable dt = null;
using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select CountryName from Country";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
dt = new DataTable();
da.Fill(dt);
}
}
}
StringBuilder output = new StringBuilder();
output.Append("[");
for (int i = 0; i < dt.Rows.Count; ++i)
{
output.Append("\"" + dt.Rows[i]["CountryName"].ToString() + "\"");
if (i != (dt.Rows.Count - 1))
{
output.Append(",");
}
}
output.Append("];");
return output.ToString();
}
}
RESULT :