Search This Blog

Monday, June 4, 2012

Using Auto-Complete From Ajax Control Toolkit:


AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup panel to display words that begin with the prefix typed into the textbox.

To Use it We first download Ajax control toolkit, then create a new empty website, in website we add new tab in toolkit section, in this tab we will add control my choosing dll from Ajax control toolkit’s unzipped folder.
   Now to in our website we will add a simple aspx page, to use Ajax control first we need to include script manager so add script manager to our aspx page.

As

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

Let’s add textbox to page as

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

To add auto complete feature we need to use auto complete extender for that either use smart tag by taking mouse over textbox add selecting add extender ,select auto complete extender from extender list

Or directly add tags corresponding to it as follows

  <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
            Enabled="True"
            ServicePath="~/Default.aspx"
            ServiceMethod="SearchScrip"
            TargetControlID="TextBox1"
            CompletionInterval="100"
            EnableCaching="false"
            CompletionSetCount="5"
            MinimumPrefixLength="2">
        </asp:AutoCompleteExtender>

Here AutoCompleteExtender has many attributes we are not using all of this in this example.

a)    MinimumPrefixLength: This specifies length of string written in textbox after which auto-completion get enabled.
b)      CompletionSetCount: This tells about number of suggestions to be retrieved from the web service.
c)      ServiceMethod - The web service method to be called. The signature of this method must match the following:



[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string [] MethodName (string prefixText, int count) 
{ 
  //some code here
}
d)       ServicePath - The path to the web service that the extender will pull the word\sentence completions from. If this is not provided, the service method should be a page method.
e)      EnableCaching - Whether client side caching is enabled.
f)        TargetControlID - The TextBox control where the user types content to be automatically completed
g)      CompletionInterval - Time in milliseconds when the timer will kick in to get suggestions using the web service.
h)      ContextKey - User/page specific context provided to an optional overload of the web method described by ServiceMethod/ServicePath. If the context key is used, it should have the same signature with an additional parameter named contextKey of type string:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] MethodName (
    string prefixText, int count, string contextKey) 
     { 
       //some code here
     }
i)        UseContextKey - Whether or not the ContextKey property should be used. This will be automatically enabled if the ContextKey property is ever set (on either the client or the server). If the context key is used, it should have the same signature with an additional parameter named contextKey of type string (as described above).
j)        FirstRowSelected - Determines if the first option in the AutoComplete list will be selected by default.
k)      DelimiterCharacters - Specifies one or more character(s) used to separate words. The text in the AutoComplete textbox is tokenized using these characters and the webservice completes the last token.
l)        ShowOnlyCurrentWordInCompletionListItem - If true and DelimiterCharacters are specified, then the AutoComplete list items display suggestions for the current word to be completed and do not display the rest of the tokens.


In my case webservice is written in a aspx page itself instead of asmx page code for same is bellow and service method name is SearchScrip and service path is  Default.aspx

[System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> SearchScrip(string prefixText, int count)
    {
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = "Server=CONFLUX-D07A835;integrated security=sspi;initial catalog=FinDomain;";
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "ScripName";
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Script", prefixText);
                cmd.Connection = conn;
                conn.Open();
                List<string> StringList = new List<string>();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        StringList.Add(sdr["SC_NAME"].ToString());
                    }
                }
                conn.Close();
                return StringList;
            }
        }
    }

In this service method I am calling a stored procedure ScripName which takes single parameter and do like search on it

By constructing query like

select SC_NAME from dbo.BseBhavCopy where SC_NAME like  @Script + '%'

Where @Script is input parameter of stored procedure.

BseBhavCopy is a table obtained by uploading BSE equity bhavcopy to sql server.

Now when we run our application we will get auto complete to textbox1.


Using Context attribute of auto complete extender : To use context attribute we will modify our code add add Context key as nse

<asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
            Enabled="True"
            ServicePath="~/Default.aspx"
            ServiceMethod="SearchScrip"
            TargetControlID="TextBox1"
            CompletionInterval="100"
            EnableCaching="false"
            CompletionSetCount="5"
            MinimumPrefixLength="2"
            ContextKey="NSE"
            />

This will demand an overload of earlier webservice method with additional parameter for context as follows

[System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> SearchScrip(string prefixText, int count, string contextKey)
    {
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = "Server=CONFLUX-D07A835;integrated security=sspi;initial catalog=FinDomain;";
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "ScripName";
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Script", prefixText);
                cmd.Parameters.AddWithValue("@Exchange", contextKey);
                cmd.Connection = conn;
                conn.Open();
                List<string> StringList = new List<string>();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        StringList.Add(sdr["SC_NAME"].ToString());
                    }
                }
                conn.Close();
                return StringList;
            }
        }
    }

Now when we run our code second service method get called,real use of context can be thought out as suppose you have two textboxes one for nse scrip & second for bse scrip
Still we can use single sevice for both of them only thing is that corresponding AutoCompleteExtender have different ContextKey say NSE & BSE.

We can add bit of animation to auto complete ,add style that we will use to show when our query will take long time to fetch data,also add OnClientPopulating & OnClientCompleted javascript methods

    <style type="text/css">
    .loading
    {
        background-image: url(images/loading.gif);
        background-position: right;
        background-repeat: no-repeat;
    }
    </style>

    <script type="text/javascript">
        function OnClientPopulating(sender, e) {
            sender._element.className = "loading";
        }
        function OnClientCompleted(sender, e) {
            sender._element.className = "";
        }
</script>

Now our ajax extender tag look like

<asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
            Enabled="True"
            ServicePath="~/Default.aspx"
            ServiceMethod="SearchScrip"
            TargetControlID="TextBox1"
            CompletionInterval="100"
            EnableCaching="false"
            CompletionSetCount="5"
            MinimumPrefixLength="2"
            ContextKey="NSE"
            OnClientHiding="OnClientCompleted"
            OnClientPopulated="OnClientCompleted"
            OnClientPopulating="OnClientPopulating">
            <Animations>
                <OnHide>
                  <FadeOut Duration=".5" Fps="20" />
                </OnHide>
            </Animations>
            </asp:AutoCompleteExtender>

Ensure that loading.gif animated gif exist in images folder whenever we run new code for fraction of second you see animated gif

   Animation tag can have OnShow & OnHide tags to which we can add some animation effect, we will explore this part latter.

References: