Search code examples
asp.net-ajaxasp.net-3.5autocompleteextender

Asp.net using AutoCompleteExtender


I want to use AutoCompleteExtender with textbox to auto complete user's entry from mysql database.

but the problem when I run the code and enter a litter should call the webservice method but the problem that the service method return nothing here is my code so please advice me.

<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />

    </div>
    <div>
        <asp:UpdatePanel id="UPSearch" runat="server">
            <ContentTemplate>
                <asp:Panel runat="server" style="position:absolute; top: 48px; left: 10px;">
                    <asp:TextBox ID="txtSearch" runat="server" 
                        style="position:absolute; top: 17px; left: 235px;"></asp:TextBox>
                    <cc1:AutoCompleteExtender ID="ACE_txtSearch" runat="server" TargetControlID="txtSearch" ServiceMethod= "GetByLastName" ServicePath="SearchService.asmx" MinimumPrefixLength="1" >
                    </cc1:AutoCompleteExtender>
                     <asp:RadioButton ID="rdoLastName" runat="server" 
                        style="position:absolute; top: 96px; left: 224px; width: 186px;" 
                        Text="Search By Last Name"/>

                </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>

Web Service

namespace Imam_Contacts
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]

    public class SearchService : System.Web.Services.WebService
    {


        [WebMethod]
        public string[] GetByLastName(string prefixText)
        {
         int count = 10;
         string sql = "Select * from contact_info Where Last_Name like @prefixText";
         SqlDataAdapter da = new SqlDataAdapter(sql,"server=localhost;User Id=root;database=contacts;Persist Security Info=True");
         da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%"; 
         DataTable dt = new DataTable(); 
         da.Fill(dt); 

         string[] items = new string[dt.Rows.Count];
         int i = 0; 
         foreach (DataRow dr in dt.Rows) 
         {
             items.SetValue(dr["Last_Name"].ToString(), i); 
             i++; 
         } 
         return items; 
        }
    }
}

Solution

  • This answer is only relevant if you can't find a better solution but I'd highly recommend using jQuery and one of the many autocomplete plugins it has available. It's far more reliable and much more customizable.