Tuesday, July 2, 2013

How to use AutoCompleteExtender Ajax Control in Asp.net OR AutoCompleteExtender Ajax Control Example

Introduction: In this post I will try to explain how we can use the AutoCompleteExtender Ajax Control in Asp.net.


In the last article I have explained How to install Ajax control Toolkit in Visual Studio , How to upload multiple files using AjaxFileUpload and save path to Database in asp.net , How to use Ajax UpdateProgress Control in Asp.net.

I have a table PRODUCTS. Here PRODUCT_ID is primary key and auto increment.


Add a webform to project. Drag and drop the AutoCompleteExtender ,  ScriptManager control from Toolbox as mention below:

<table border="1px solid">
    <tr><b>AutoCompleteExtender Example</b></tr>
    <tr><td>Product Name:</td><td><asp:TextBox ID="txtproduct" runat="server"></asp:TextBox></td></tr></table>   
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtproduct" ServiceMethod="GETPRODUCT" MinimumPrefixLength="1" EnableCaching="false" CompletionSetCount="10" CompletionInterval="100"></asp:AutoCompleteExtender>

Now go to .aspx.cs page and write the below given code:

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

    public static List<string> GETPRODUCT(string prefixText, int count)
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
        SqlCommand cmd = new SqlCommand("Select * from PRODUCTS where PRODUCT_NAME like @PRODUCT_NAME+'%'", con);
        cmd.Parameters.AddWithValue("@PRODUCT_NAME", prefixText);
        List<string> productname = new List<string>();
        SqlDataReader dr = cmd.ExecuteReader();     
      if (dr.HasRows)
          while (dr.Read())

      return productname;

In VB (.aspx.vb)

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

<System.Web.Script.Services.ScriptMethod()> _
 <System.Web.Services.WebMethod()> _
    Public Shared Function GETPRODUCT(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
        Dim cmd As New SqlCommand("Select * from PRODUCTS where PRODUCT_NAME like @PRODUCT_NAME+'%'", con)
        cmd.Parameters.AddWithValue("@PRODUCT_NAME", prefixText)
        Dim productname As New List(Of String)()
        Dim dr As SqlDataReader = cmd.ExecuteReader()
        If dr.HasRows Then
            While dr.Read()
            End While
        End If
        Return productname
    End Function

Now run the project and check the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment