"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Thursday, July 22, 2010

Auto complete in asp.net c# using jquery with sample

 hi friends,
previously i show how to do auto complete in .net using ajax.2day I'm using j query instead of Ajax.Just sample idea :)
demo

documentation

For this u need 2 js file( jquery-1.3.2.js, jquery.autocomplete.js ) 'n 1 css(jquery.autocomplete.css and an image( throbber.gif ) all are important.Create a normal textbox and paste this code just after closing the div
     <script type="text/javascript">
        $(document).ready(function() {
            $("#txtAutoComplete").autocomplete("AutoCompleteHandler.ashx", {
                width: 200,
                scroll: false
            });
        });
</script>

Note:
txtAutoComplete:- is my textbox name
AutoCompleteHandler.ashx:- is my generic handler file name

actually the code is sending the value to jquery.
on the generic handler we get the value by query string and their i use like query to my database and store all my relevant data in string array.and taking the count of data if their is no data i show a flag. code of that

public string[] items;
    public void ProcessRequest(HttpContext context)
    {
        string strData = string.Empty;
         string s=string.Empty;
        if (context.Request.QueryString["q"] != null)
        {
            string q = context.Request.QueryString["q"].Trim();
            string limit = context.Request.QueryString["limit"];

            string sql = "Select * from mst_tble Where strcountry like '"+q+"%'";
            SqlDataAdapter da = new SqlDataAdapter(sql, "Password=****;User ID=sa;Initial Catalog=country;Data Source=localhost");
            DataTable dt = new DataTable();
            da.Fill(dt);
            // items = new string[dt.Rows.Count];
            items=new string[dt.Rows.Count ==0?1:dt.Rows.Count];
            int i = 0;
            if(dt.Rows.Count==0)
            {
                    items.SetValue("No Match Found", i);
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(Environment.NewLine);
                    context.Response.Write(items[i].ToString()); 
            }
            else
            {  
                foreach (DataRow dr in dt.Rows)
                {
                    items.SetValue(dr["strcountry"].ToString(), i);
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(Environment.NewLine);
                    context.Response.Write(items[i].ToString());
                    i++;
                }
            }
        }

sample 
 

Hope it help u some times.Have a nice day... 'N happy Coding :)

jQuery Cookbook: Solutions & Examples for jQuery Developers (Animal Guide)jQuery in Action, Second EditionjQuery UI 1.7: The User Interface Library for jQuery 

No comments: