How to create a textbox with autocomplete using ajax in asp.net c#
Step 1: Open MS SQL Server Management 2008 R2 and create one table with your columns.
Here,i used two columns namely like id, name.
[That name i want to show in auto complete mode]
Step 2: Open vs 2008 and create a new web site / web application
Step 3: Add New page named as ajaxPage.aspx
Step 4: and then create connection string
Step 5: Now open Default.aspx and do follwoing.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete</title>
<script type="text/javascript" language="javascript">
var xmlHTTP, objven, dwncnt = 0, event1, ctnt, newLik, lengthoflike, oVendiv, position1, position2, txtValue, txtID;
function Trim(str) {
while (true) {
if (str.charAt(0) == ' ')
str = str.substr(1);
else
break;
}
while (true) {
if (str.charAt(str.length - 1) == ' ')
str = str.substr(0, str.length - 1);
else
break;
}
return (str);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//start auto complete
function fun_RelatedNames(getval, evt) {
var pos = findPos(getval);
txtID = getval.id;
position1 = pos[0];
position2 = pos[1];
document.getElementById(txtID).value = Trim(document.getElementById(txtID).value);
txtVal = document.getElementById(txtID).value;
event1 = evt;
objven = getval;
if (window.event != undefined) {
kc = window.event.keyCode;
}
else {
kc = evt.keyCode;
}
newLik = txtVal.split(",");
for (k = 0; k < newLik.length; k++) {
txtVal = newLik[k];
lengthoflike = newLik[k].length
}
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "AjaxPage.aspx?txtValue=" + txtVal; //Note Here i passed textbox value like 'a' / 'b'..
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = stateChangednewvenEmpty;
xmlHttp.send(null);
return false;
}
//End autocomplete
function stateChangednewvenEmpty() {
if (xmlHttp.readyState == 4) {
if (document.getElementById('vendiv') != undefined) {
document.body.removeChild(oVendiv);
}
if (xmlHttp.responseText == "0") {
return false;
}
oVendiv = document.createElement("DIV");
oVendiv.innerHTML = xmlHttp.responseText;
oVendiv.style.position = "absolute";
oVendiv.style.top = position2 + 20 + 'px';
oVendiv.style.left = position1 + 'px';
oVendiv.style.width = '170px';
oVendiv.setAttribute('id', 'vendiv');
oVendiv.style.overflow = "hidden";
oVendiv.style.visibility = "visible";
oVendiv.style.background = '#FFFFFF';
oVendiv.style.fontFamily = "Verdana";
oVendiv.style.fontSize = '13px';
oVendiv.style.cursor = 'pointer';
oVendiv.style.border = 'solid Black 1px';
document.body.appendChild(oVendiv);
var footval = Trim(document.getElementById(txtID).value);
if (footval == "") {
document.body.removeChild(oVendiv);
return false;
}
if (kc == 40) {
dwncnt = dwncnt + 1;
ctnt = dwncnt;
if (dwncnt > 12) {
dwncnt = 0;
}
var pick = "pick" + dwncnt;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#8A95E1";
}
}
if (kc == 38) {
if (dwncnt > 0) {
dwncnt = dwncnt - 1;
}
var pick = "pick" + dwncnt;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#8A95E1";
}
}
if (kc == 8) {
dwncnt = 0;
}
if (kc == 46) {
dwncnt = 0;
}
if (kc == 48) {
var pick = "pick" + dwncnt;
if (document.getElementById(pick) != undefined) {
}
}
if (kc == 13) {
_Selectedneww(ctnt);
}
if (kc == 27) {
document.body.removeChild(oVendiv);
}
}
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
function _Chooseneww(len) {
var pick = "pick" + len;
var hidfilter = "hidven" + len;
var hiddisc = "hidvendisc" + len;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#8A95E1";
document.getElementById(pick).style.fontColor = "#ff0000";
if (newLik.length == 1) {
objven.value = document.getElementById(hidfilter).value;
}
else {
objven.value = objven.value + document.getElementById(hidfilter).value.substring(lengthoflike, document.getElementById(hidfilter).value.length);
}
dwncnt = 0;
}
}
function _Removeneww(len) {
var pick = "pick" + len;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#FFFFFF";
document.getElementById(pick).style.foreColor = "";
}
}
function _Selectedneww(len) {
var pick = "pick" + len;
var hidfilter = "hidven" + len;
var hiddisc = "hidvendisc" + len;
if (document.getElementById(pick) != undefined) {
if (newLik.length == 1) {
objven.value = document.getElementById(hidfilter).value;
}
else {
objven.value = objven.value + document.getElementById(hidfilter).value.substring(lengthoflike, document.getElementById(hidfilter).value.length);
}
dwncnt = 0;
if (document.getElementById('vendiv') != undefined) {
document.body.removeChild(oVendiv);
}
}
}
function RemoveAjax() {
document.getElementById('txt_ac').value = Trim(document.getElementById('txt_ac').value);
if (document.getElementById('txt_ac').value != "") {
if (document.getElementById('vendiv') != undefined) {
document.body.removeChild(oVendiv);
}
return false;
}
}
function removediv() {
document.body.removeChild(oVendiv);
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" width="96%" align="center">
<tr>
<td>
</td>
</tr>
<tr>
<td align="center">
<asp:TextBox ID="txt_ac" runat="server" onkeyup="return fun_RelatedNames(this,event);"
onblur="return RemoveAjax();"></asp:TextBox>
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
step 6 : Now add new page named as AjaxPage.aspx
step 7 : delete all aspx codings except following directive;
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
step 8 : AjaxPage.aspx.cs in that page do following things:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class AjaxPage : System.Web.UI.Page
{
string conStr = ConfigurationManager.ConnectionStrings["testCon"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter sqlda;
DataTable dt;
DataTable dt1;
DataSet ds;
int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
Response.ContentType = "text/xml";
if (!IsPostBack)
{
Response.Expires = -1;
Response.ContentType = "text/xml";
using (con = new SqlConnection(conStr))
{
con.Open();
string selQry = "select name from testAjax where name like @name+'%' ";
using (cmd = new SqlCommand(selQry, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("name", Request.QueryString[0]);
sqlda = new SqlDataAdapter(cmd);
dt = new DataTable();
sqlda.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Response.Write("<table border='0' cellspacing='0' cellpadding='0' width='100%'>");
foreach (DataRow dr in dt.Rows)
{
i = i + 1;
Response.Write("<tr id='pick" + i + "' onMouseMove='_Chooseneww(" + i + ")' onMouseOut='_Removeneww(" + i + ")' style='cursor:hand' onClick='_Selectedneww(" + i + ")' >");
Response.Write("<td><input type='hidden' name='hidven" + i + "' id='hidven" + i + "' value='" + dr[0].ToString() + "'></td>");
Response.Write("<td><input type='hidden' name='hidvendisc" + i + "' id='hidvendisc" + i + "' value='" + dr[0].ToString() + "'></td>");
Response.Write("<td align='left'> " + dr[0].ToString() + "</td>");
Response.Write("</tr>");
}
Response.Write("</table>");
}
else
{
Response.Write("<table border='0' cellspacing='0' cellpadding='0' width='100%'>");
Response.Write("<tr id='pick" + i + "' onMouseOut='removediv()' style='cursor:hand' >");
Response.Write("<td align='left'>Not Matched</td>");
Response.Write("</tr>");
Response.Write("</table>");
return;
}
}
}
}
Output :
Step 1: Open MS SQL Server Management 2008 R2 and create one table with your columns.
Here,i used two columns namely like id, name.
[That name i want to show in auto complete mode]
Step 2: Open vs 2008 and create a new web site / web application
Step 3: Add New page named as ajaxPage.aspx
Step 4: and then create connection string
Step 5: Now open Default.aspx and do follwoing.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete</title>
<script type="text/javascript" language="javascript">
var xmlHTTP, objven, dwncnt = 0, event1, ctnt, newLik, lengthoflike, oVendiv, position1, position2, txtValue, txtID;
function Trim(str) {
while (true) {
if (str.charAt(0) == ' ')
str = str.substr(1);
else
break;
}
while (true) {
if (str.charAt(str.length - 1) == ' ')
str = str.substr(0, str.length - 1);
else
break;
}
return (str);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//start auto complete
function fun_RelatedNames(getval, evt) {
var pos = findPos(getval);
txtID = getval.id;
position1 = pos[0];
position2 = pos[1];
document.getElementById(txtID).value = Trim(document.getElementById(txtID).value);
txtVal = document.getElementById(txtID).value;
event1 = evt;
objven = getval;
if (window.event != undefined) {
kc = window.event.keyCode;
}
else {
kc = evt.keyCode;
}
newLik = txtVal.split(",");
for (k = 0; k < newLik.length; k++) {
txtVal = newLik[k];
lengthoflike = newLik[k].length
}
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "AjaxPage.aspx?txtValue=" + txtVal; //Note Here i passed textbox value like 'a' / 'b'..
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = stateChangednewvenEmpty;
xmlHttp.send(null);
return false;
}
//End autocomplete
function stateChangednewvenEmpty() {
if (xmlHttp.readyState == 4) {
if (document.getElementById('vendiv') != undefined) {
document.body.removeChild(oVendiv);
}
if (xmlHttp.responseText == "0") {
return false;
}
oVendiv = document.createElement("DIV");
oVendiv.innerHTML = xmlHttp.responseText;
oVendiv.style.position = "absolute";
oVendiv.style.top = position2 + 20 + 'px';
oVendiv.style.left = position1 + 'px';
oVendiv.style.width = '170px';
oVendiv.setAttribute('id', 'vendiv');
oVendiv.style.overflow = "hidden";
oVendiv.style.visibility = "visible";
oVendiv.style.background = '#FFFFFF';
oVendiv.style.fontFamily = "Verdana";
oVendiv.style.fontSize = '13px';
oVendiv.style.cursor = 'pointer';
oVendiv.style.border = 'solid Black 1px';
document.body.appendChild(oVendiv);
var footval = Trim(document.getElementById(txtID).value);
if (footval == "") {
document.body.removeChild(oVendiv);
return false;
}
if (kc == 40) {
dwncnt = dwncnt + 1;
ctnt = dwncnt;
if (dwncnt > 12) {
dwncnt = 0;
}
var pick = "pick" + dwncnt;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#8A95E1";
}
}
if (kc == 38) {
if (dwncnt > 0) {
dwncnt = dwncnt - 1;
}
var pick = "pick" + dwncnt;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#8A95E1";
}
}
if (kc == 8) {
dwncnt = 0;
}
if (kc == 46) {
dwncnt = 0;
}
if (kc == 48) {
var pick = "pick" + dwncnt;
if (document.getElementById(pick) != undefined) {
}
}
if (kc == 13) {
_Selectedneww(ctnt);
}
if (kc == 27) {
document.body.removeChild(oVendiv);
}
}
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
function _Chooseneww(len) {
var pick = "pick" + len;
var hidfilter = "hidven" + len;
var hiddisc = "hidvendisc" + len;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#8A95E1";
document.getElementById(pick).style.fontColor = "#ff0000";
if (newLik.length == 1) {
objven.value = document.getElementById(hidfilter).value;
}
else {
objven.value = objven.value + document.getElementById(hidfilter).value.substring(lengthoflike, document.getElementById(hidfilter).value.length);
}
dwncnt = 0;
}
}
function _Removeneww(len) {
var pick = "pick" + len;
if (document.getElementById(pick) != undefined) {
document.getElementById(pick).style.backgroundColor = "#FFFFFF";
document.getElementById(pick).style.foreColor = "";
}
}
function _Selectedneww(len) {
var pick = "pick" + len;
var hidfilter = "hidven" + len;
var hiddisc = "hidvendisc" + len;
if (document.getElementById(pick) != undefined) {
if (newLik.length == 1) {
objven.value = document.getElementById(hidfilter).value;
}
else {
objven.value = objven.value + document.getElementById(hidfilter).value.substring(lengthoflike, document.getElementById(hidfilter).value.length);
}
dwncnt = 0;
if (document.getElementById('vendiv') != undefined) {
document.body.removeChild(oVendiv);
}
}
}
function RemoveAjax() {
document.getElementById('txt_ac').value = Trim(document.getElementById('txt_ac').value);
if (document.getElementById('txt_ac').value != "") {
if (document.getElementById('vendiv') != undefined) {
document.body.removeChild(oVendiv);
}
return false;
}
}
function removediv() {
document.body.removeChild(oVendiv);
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" width="96%" align="center">
<tr>
<td>
</td>
</tr>
<tr>
<td align="center">
<asp:TextBox ID="txt_ac" runat="server" onkeyup="return fun_RelatedNames(this,event);"
onblur="return RemoveAjax();"></asp:TextBox>
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
step 6 : Now add new page named as AjaxPage.aspx
step 7 : delete all aspx codings except following directive;
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
step 8 : AjaxPage.aspx.cs in that page do following things:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class AjaxPage : System.Web.UI.Page
{
string conStr = ConfigurationManager.ConnectionStrings["testCon"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter sqlda;
DataTable dt;
DataTable dt1;
DataSet ds;
int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
Response.ContentType = "text/xml";
if (!IsPostBack)
{
Response.Expires = -1;
Response.ContentType = "text/xml";
using (con = new SqlConnection(conStr))
{
con.Open();
string selQry = "select name from testAjax where name like @name+'%' ";
using (cmd = new SqlCommand(selQry, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("name", Request.QueryString[0]);
sqlda = new SqlDataAdapter(cmd);
dt = new DataTable();
sqlda.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Response.Write("<table border='0' cellspacing='0' cellpadding='0' width='100%'>");
foreach (DataRow dr in dt.Rows)
{
i = i + 1;
Response.Write("<tr id='pick" + i + "' onMouseMove='_Chooseneww(" + i + ")' onMouseOut='_Removeneww(" + i + ")' style='cursor:hand' onClick='_Selectedneww(" + i + ")' >");
Response.Write("<td><input type='hidden' name='hidven" + i + "' id='hidven" + i + "' value='" + dr[0].ToString() + "'></td>");
Response.Write("<td><input type='hidden' name='hidvendisc" + i + "' id='hidvendisc" + i + "' value='" + dr[0].ToString() + "'></td>");
Response.Write("<td align='left'> " + dr[0].ToString() + "</td>");
Response.Write("</tr>");
}
Response.Write("</table>");
}
else
{
Response.Write("<table border='0' cellspacing='0' cellpadding='0' width='100%'>");
Response.Write("<tr id='pick" + i + "' onMouseOut='removediv()' style='cursor:hand' >");
Response.Write("<td align='left'>Not Matched</td>");
Response.Write("</tr>");
Response.Write("</table>");
return;
}
}
}
}
Output :
Comments
Post a Comment