Tuesday 24 July 2012

Autocomplete textbox with database in asp.net


Simple Steps to have autocomplete text box

code is as follows

Steps
1.Add autocomplete extender to the text box.

2. <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCountry"
MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCountries" >
</asp:AutoCompleteExtender>


3.Write this code in the .cs page where you have added autocompletetext box.


 [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<string> GetCountries(string prefixText)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection1"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from banks where name like @Name+'%'", con);
            cmd.Parameters.AddWithValue("@Name", prefixText);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<string> name = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                name.Add(dt.Rows[i][1].ToString());
            }
            return name;
        }

Change the table name and other things. no need to have .asmx.cs file.