Sunday, 5 June 2011

Ajax AutoComplete Exender with Database Connectivity


Default.aspx
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1"
            ServicePath="WebService.asmx" ServiceMethod="GetNames" MinimumPrefixLength="0"
            CompletionInterval="100" EnableCaching="true" CompletionSetCount="12">
        </asp:AutoCompleteExtender>
    </div>
    </form>
</body>
</html>

WebService.cs

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

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

    public WebService()
    {

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

    [WebMethod]
    public string[] GetNames(string prefixText, int count)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
        count = 10;
        string str = "SELECT * FROM student WHERE sname like '" + prefixText + "%'";
        con.Open();
        SqlCommand com = new SqlCommand(str, con);
        SqlDataReader dr = com.ExecuteReader();
        int i = 0;
        ArrayList AlNames = new ArrayList();
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                string StrTemp = dr["sname"].ToString();
                AlNames.Add(StrTemp);
                i++;
            }
        }
        return AlNames.ToArray(typeof(string)) as string[];
    }
}

No comments:

Post a Comment