SIGN UP MEMBER LOGIN:    
ARTICLE

Country & State Using AutoCompleteExtender

Posted by Vidya Rani Articles | ASP.NET Programming November 12, 2011
This article shows how to create and use of AutoCompleteExtender to display Country and States.
Reader Level:
Download Files:
 

Introduction:

This article shows how to create and use AutoCompleteExtender to display Country and States. When you are typing in txtCountry, it will list out all country names that start with the typed characters, and then when you are typing in txtStates, it will list out all States for that Country (txtCountry). 

Step 1: Create a table for Country and State

 tbl_country Table

Create Table tbl_Country
(

     Cid 
Int Primary Key,
     cname 
Varchar(30)
)

tbl_state Table

Create Table tbl_State
(

     sid 
Int Primary Key,
     cid 
Int Foreign Key References tbl_Country(cid),
     sname
 Varchar(30)
)

1.gif

Now drag and drop the two textboxes and two AutoCompleteExtenders

.aspx code :

In the below source code I used JQuery to pass id of the country to another autocomplete extender (acestate).

eventArgs.get_value() The method will return id of selected country (acecountry).

TargetControlID: The textbox control where user type content  to be automatically completed.

OnClientItemSelected: It will call the client side javascript method to set contexKey to another AutoCompleteExtender(acestate).

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%
@ 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></title>

    <script src="jquery-1.5.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        function IAmSelected(source, eventArgs) {

            $find('acestate').set_contextKey(eventArgs.get_value());

        }
    </script>

</head>
<
body>
    <form id="form1" runat="server">

    <div>

        <asp:ScriptManager runat="server" ID="sc">

            <Services>

                <asp:ServiceReference Path="~/WebService.asmx" />

            </Services>

        </asp:ScriptManager>

        <table>

            <tr>

                <td>

                    <asp:Label Text="Country" ID="lblcountry" runat="server"></asp:Label>

                </td>

                <td>

                    <asp:UpdatePanel runat="server" ID="Up1" UpdateMode="Conditional">

                        <ContentTemplate>

                            <asp:TextBox runat="server" ID="txtcountry"></asp:TextBox>

                            <div>

                                <cc1:AutoCompleteExtender runat="server" ID="acecountry" TargetControlID="txtcountry"

                                    MinimumPrefixLength="1" ServiceMethod="GetCountryList" ServicePath="WebService.asmx"

                                    EnableCaching="true" OnClientItemSelected="IAmSelected">

                                </cc1:AutoCompleteExtender>

                            </div>

                        </ContentTemplate>

                    </asp:UpdatePanel>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label runat="server" ID="lblstate" Text="State"></asp:Label>

                </td>

                <td>

                    <asp:UpdatePanel runat="server" ID="up2" UpdateMode="Conditional">

                        <ContentTemplate>

                            <asp:TextBox runat="server" ID="txtstate"></asp:TextBox>

                            <cc1:AutoCompleteExtender runat="server" ID="acestate" TargetControlID="txtstate"

                                MinimumPrefixLength="1" ServicePath="WebService.asmx" UseContextKey="true" ServiceMethod="GetStatesList"

                           
</cc1:AutoCompleteExtender>                       
                        </ContentTemplate>

                    </asp:UpdatePanel>

                </td>

            </tr>

        </table>

    </div>

    </form>

</
body>
</
html>

Create one webservice in the  website,  name it as WebService.cs. And add the two service methods in that webservice.  Here, the server side methods will return an array of strings.

GetCountryList:

The below method is used to get list of Country names from the database whose letters starts with prefixText

Note : Dont forget to add [System.Web.Script.Services.ScriptService]  to  Web service  class, because if want to access service through asp.net AJAX we have to add above line

[WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] GetCountryList(string prefixText)
    {
       
SqlConnection con = new SqlConnection("connection string");
        SqlDataAdapter dad = new SqlDataAdapter("select cname,cid from tbl_country where cname like '" + prefixText + "%'", con);
        DataSet ds = new DataSet();
        dad.Fill(ds);
        List<string> list = new List<string>(ds.Tables[0].Rows.Count);
       
foreach (DataRow dr in ds.Tables[0].Rows)
        {
            list.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr[0].ToString(), dr[1].ToString()));

        }

        return list.ToArray();
    }

GetStatesList:  Used to get list of state for that particular country  from database. Here country id is availble in ContextKey parameter of GetStatesList so that we can filter state by country id and prefixText.

[WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] GetStatesList(string prefixText, int count, string contextKey)
    {
        SqlConnection con = new SqlConnection("connection string");
        SqlDataAdapter dad = new SqlDataAdapter("select sname,sid from tbl_state where cid=" + contextKey + "and  sname like '" + prefixText + "%'", con);
        DataSet ds = new DataSet();
        dad.Fill(ds);
        List<string> list = new List<string>(ds.Tables[0].Rows.Count);

        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            list.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr[0].ToString(), dr[1].ToString()));
        }
        return list.ToArray();
    }

Now run the application and test it , first type 'I' letter in txtcountry textbox then it will list out all country names whose letter statrs with 'I'.

2.gif

Now type 'A' in txtstate textbox it will list out all state names  for a particular country (ex:India).

3.gif

Note: It is very important that you keep the signature of the method same as what given above. The method must have two parameters namely.

  1. prefixText (string)
  2. count (int)
  3. contextKey(string)

Otherwise the method won't work with AutoCompleteExtender. You can see the demo of this article by downloading this application.

Login to add your contents and source code to this article
share this article :
post comment
 

ThankQ RAj

Posted by Vidya Rani Nov 17, 2011

Good article Vidya Rani and very usefull too.

Posted by Raj Kumar Nov 17, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor