Monday 28 May 2012

Auto Complete TextBox Database Driven Data and using ajax toolkit

Step 1: Ajax Toolkit added
Step 2: Design Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="autocomplete.aspx.cs" Inherits="autocomplete" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<!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:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <cc1:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
            MinimumPrefixLength="2" CompletionInterval="2" EnableCaching="true" CompletionSetCount="3"
            DelimiterCharacters="" Enabled="True" ServiceMethod="GetCompletionList"
            ServicePath="" TargetControlID="TextBox1" UseContextKey="True"
            FirstRowSelected="True">
        </cc1:AutoCompleteExtender>
   
    </div>
    </form>
</body>
</html>
Step 3: Code Side


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;
using System.Collections.Generic;

public partial class autocomplete : System.Web.UI.Page
{
    public static SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Con"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        autocomplete obj = new autocomplete();

        SqlConnection con1 = new SqlConnection(ConfigurationManager.AppSettings["Con"].ToString());
        SqlCommand cmd = new SqlCommand("SELECT top 5 name from msppt_com_impact.ASAXPartnerEDM_Reg WHERE name LIKE '" + prefixText + "%'", con1);
        SqlDataReader oReader;
        con1.Open();
        List<string> CompletionSet = new List<string>();
        oReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (oReader.Read())
            CompletionSet.Add(oReader["name"].ToString());
        return CompletionSet.ToArray();
        //return default(string[]);
    }
}

No comments:

Post a Comment