Share Blog

Saturday, December 26, 2015

JQuery Bootstrap Autocomplete Textbox from Database Example in Asp.net using C#

Before Implement This Example First Create One Table Leader in your  SQL Database like as Shown Below

CREATE TABLE Leader(
      [LeaderId] [int] IDENTITY(1,1)Primary Key NOT NULL,
      [Leader_Name] [nvarchar](150) NULL,
      [State] [nvarchar](150) NULL,
      [Lok_Sabha_Place] [nvarchar](150) NULL
)



Once we design table in our Database insert some data in your table to use it in our application that would be like as shown below



Now open your aspx page and write the code like as shown below

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

<!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>Bootstrap Autocomplete Textbox Example in Asp.net Using C#</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel = "Stylesheet" href = "https://twitter.github.io/typeahead.js/css/examples.css"></link>

<script type="text/javascript">
    $(function () {
        $('#txtSearch').keyup(function () {
            $.ajax({
                url: "AutocompleteTextbox .aspx/GetAutoCompleteData",
                data: "{'username':'" + $('#txtSearch').val() + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var val = '<ul id="userlist">';
                    $.map(data.d, function (item) {
                        var itemval = item.split('/')[0];
                        val += '<li class=tt-suggestion>' + itemval + '</li>'
                    })
                    val += '</ul>'
                    $('#divautocomplete').show();
                    $('#divautocomplete').html(val);
                    $('#userlist li').click(function () {
                        $('#txtSearch').val($(this).text());
                        $('#divautocomplete').hide();
                    })
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        })
        $(document).mouseup(function (e) {
            var closediv = $("#divautocomplete");
            if (closediv.has(e.target).length == 0) {
                closediv.hide();
            }
        });
    });
</script>
<style type="text/css">
ul li
{
list-style: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="position: absolute;left: 30%; z-index: 100; text-align:left;">

    <asp:TextBox ID="txtSearch" runat="server" class="typeahead" placeholder="Type Leader Name to search" autocomplete="off" ></asp:TextBox>
<div id="divautocomplete" class="tt-menu" style="display:none">
</div>
</div>
</form>
</body>
</html>

Now add following namespaces in code behind

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

After completion of adding namespaces you need to write the code like as shown below

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

public partial class AutocompleteTextbox_ : System.Web.UI.Page
{
    //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection("Data Source=lENOVO-pC;Initial Catalog=Digital_Politices;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("select LeaderId,Leader_Name from Leader where Leader_Name LIKE '%'+@SearchText+'%'",con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", username);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(string.Format("{0}/{1}", dr["Leader_Name"], dr["LeaderId"]));
                }
                return result;
            }

        }
    }
}


DEMO


No comments:

Post a Comment