Wednesday, 11 July 2012

Ajax Autocomplete Textbox

Ajax Autocomplete Textbox In Asp.Net.


In this Article I am going to show Autocomplete Textbox using Ajax.


 .aspx page.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<%@ 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>Auto Complete</title>
    
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
    <div>
     
    <table width="100%" align="center">
    <tr>
    <td>
   
              <asp:TextBox runat="server" ID="txtcountry"></asp:TextBox>
            <cc1:AutoCompleteExtender runat="server" ID="autoCompleteExtender2" BehaviorID="autoCompleteBehavior1"
                ServiceMethod="GetCountries" MinimumPrefixLength="1"
                TargetControlID="txtcountry">
            </cc1:AutoCompleteExtender>
    </td>


    </tr>
    </table>
    </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>


.aspx.cs page
create this web method in .aspx.cs page.



[System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> GetCountries(string prefixText)
    {
        
        SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["sqlConnectionString"].ToString());
        con.Open();


        SqlCommand cmd = new SqlCommand("select * from Country_TBL where country_name like'%"+prefixText+" %' ", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        List<string> CountryNames = new List<string>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            CountryNames.Add(dt.Rows[i][0].ToString());
        }
        return CountryNames;
        con.Close();
    }


 I Hope this would be helpful to you.
 Enjoy Programming.


No comments:

Post a Comment