Monday, November 16, 2009

ASP.NET Auto Complete Extender From DB with CSS


Place this class function in App_Code folder:

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
[WebService]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
    public AutoComplete()
    {
    }
    [WebMethod]   
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString(); items.Add(strName);
        }
        return items.ToArray();
    }
    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select Distinct YourValue from YourTable where YourValue like +@Name+'%' ";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd; con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }


 add this to Auto Complete extender :


  
                    CompletionListCssClass="AutoExtender" CompletionListHighlightedItemCssClass="AutoExtenderHighlight" CompletionListItemCssClass=".AutoExtenderList"
 runat="server" TargetControlID="txtSearch"  ServicePath="AutoComplete.asmx" OnClientItemSelected=" GetCode"  ServiceMethod="GetCompletionList"
                    

CSS:


.AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
margin:0px;
            font-weight: normal;
            border:solid 1px #006699;

            line-height:20px;
            padding:0px;
            background-color:White;
        }

        .AutoExtenderList
        {
            border-bottom:dotted 1px #006699;
            cursor:pointer;
            color:Maroon;
            left:auto;
            margin:0px;
           
        }

        .AutoExtenderHighlight
        {
            color:White;
            background-color:#006699;
            cursor:pointer;
            margin:0px;
        }



To enable OnClientItemSelected write this script:
Place one hiddenfield and call the event in script




  • function GetCode(source, eventArgs) {

         $get('<%=this.HiddenField1.ClientID%>').value = eventArgs.get_value();
         $get('<%=this.ImageButton1.ClientID%>').click();

No comments: