Auto Complete TextBox in ASP.Net

Auto Complete TextBox in ASP.Net
Select event handler has been defined for the jQuery AutoComplete and when an item is selected from the AutoComplete List, the value of the item is stored in database.


Database

Source Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="autocomplete.aspx.cs" Inherits="rememberme.autocomplete" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
    $(function () {
        SearchText();
    });
    function SearchText() {
        $(".autosuggest").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "autocomplete.aspx/GetAutoCompleteData",
                    data: "{'name':'" + document.getElementById('txtSearch').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        if (data.d.length > 0) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('/')[0],
                                    val: item.split('/')[1]
                                }
                            }));
                        }
                        else {
                            response([{ label: 'No Records Found', val: -1 }]);
                        }
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            },
            select: function (event, ui) {
                if (ui.item.val == -1) {
                    return false;
                }
                $('#lblUserId').text(ui.item.val);
            }
        });
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="demo">

<asp:HiddenField ID="hdnId" runat="server" />
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
<div>&nbsp;</div>
<div>
Selected UserId:<b><label id="lblUserId" /></b>
</div>
        </div>
    </form>
</body>
</html>
C# Code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace rememberme
{
    public partial class autocomplete : System.Web.UI.Page
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static List<string> GetAutoCompleteData(string name)
        {
            List<string> result = new List<string>();
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("select name,empid from addemployee where name LIKE '%' + @SearchText + '%'", con))
                {
                    con.Open();
                    cmd.Parameters.AddWithValue("@SearchText", name);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        result.Add(string.Format("{0}/{1}", dr["name"], dr["empid"]));
                    }
                    return result;
                }
            }
        }
    }

}

Output:
Figure(1) Type Username.


Figure(2) While Typing Username it will display autocomplete in Textbox.




Figure(3) It's easier way for User to select the name.




Thanks for visiting....

Share this

Related Posts

Previous
Next Post »