Thursday 16 May 2013

Autocomplete TextBox from database using jQuery in ASP.NET

We need to jQuery package from http://jqueryui.com/ and jQuery-UI plugin and jQuery styles.
Download the packages http://jqueryui.com/autocomplete
In VS 2008 or 2010 Create web site, in the page header add jQuery packages and style as a following:

<link rel="stylesheet" href="jquery_bundle/themes/base/jquery.ui.all.css" />
<script language="javascript" type="text/javascript" src="jquery_bundle/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.core.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.widget.js"></script><script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.position.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.autocomplete.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.menu.js"></script>
<link rel="stylesheet" href="jquery_bundle/themes/demos.css" />
    <style>
     /* prevent horizontal scrollbar */
        .ui-autocomplete
        {
            max-height: 100px;
            overflow-y: auto;
            overflow-x: hidden;
        }
      * html .ui-autocomplete
        {
            height: 100px;
        }
    </style>
In the page body add TextBox Control and name it txtMemberName:

 <asp:TextBox ID="txtMemberName" runat="server" Style="padding: 5px; width: 400px;
 font: 11pt Verdana;"></asp:TextBox>
Add a webservice

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    public WebService()
    {
    }
    [WebMethod]
    public IList<string> GetAllMember(string keywords)
    {
        //TODO: implement real search here!
        IList<string> result = new List<string>();
        string constr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "select first_name from tbl_member where first_name like '%" + keywords +      "%'";
        try
        {
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                result.Add(dr["first_name"].ToString());
            }
            con.Close();
            return result;
        }
        catch
        {
            return null;
        }
    }
}
To implement autocomplete to a TextBox add the following script in the page header. This jQuery script will call the function that we declared in the web service and passing to it the typed keywords in the textbox.

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $('#<%= txtMemberName.ClientID %>').autocomplete({
            source: function(request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebService.asmx/GetAllMember",
                    data: "{'keywords':'" + request.term + "'}",
                    dataType: "json",
                    async: true,
                    success: function(data) {
                        response(data.d);
                    },
                    error: function(result) {
                        //alert("Error");
                    }
                });
            }
        });
    });
</script>





No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...