How to Use Ajax AutoCompleteExtender in Asp.Net


Description:-

In this article we will use auto complete extender to search record from database or else it will automatic display that records what you want to search from database. Here we will use Country Table to search Country Name from Database and from First Character it will search and after display records for same character. For auto complete extender we need to search record from database and return to extender.

Create Country table in your Sql Server and Fill Some Data for Search Records.

CREATE TABLE [dbo].[Country](
      [CountryID] [bigint] IDENTITY(1,1) NOT NULL,
      [CountryName] [varchar](50) NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED
(
      [CountryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Design your Webpage like below with Ajax AutoCompleteExtender.

<div>
   <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
   </asp:ScriptManager>
   <table style="margin-top: 40px; color: Black">
      <tr>
         <td>Search County</td>
         <td>
            <asp:TextBox ID="TextBox1" runat="server" Width="176px"></asp:TextBox>
            <asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server" TargetControlID="TextBox1" FirstRowSelected="false" MinimumPrefixLength="1" CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" ServiceMethod="GetCompletionList">
            </asp:AutoCompleteExtender>
         </td>
      </tr>
   </table>
</div>

Now Register AjaxControlToolKit in your Webpage like below.

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

Step 3: Now Create Method in Code behind and Name it “GetCompletionList” because we already Assign this Method in AutoCompleteExtender Property.

[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
  using (SqlConnection con = new SqlConnection())
  {
    con.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlCommand com = new SqlCommand())
    {
      com.CommandText = "select CountryName from Country where " + "CountryName like @Search + '%'";
      com.Parameters.AddWithValue("@Search", prefixText);
      com.Connection = con;
      con.Open();
      List<string> countryNames = new List<string>();
      using (SqlDataReader sdr = com.ExecuteReader())
      {
        while (sdr.Read())
        {
          countryNames.Add(sdr["CountryName"].ToString());
        }
      }
      con.Close();
      return countryNames;
    }
  }
}

Now run your Webpage in Browser and Search Country Name from Textbox. There you can get Related Characters Country Name in AutoCompleteExtender.

Related Posts

Previous
Next Post »

Thanks for comments.....