Introduction
In this article we will see how to create textboxes dynamically with autocomplete using jQuery. All of you are aware of Ajax auto-complete which we can apply for providing auto-complete for our textboxes in a ASP.Net page. In this article I'll show you another way to provide the autocomplete functionality to our textboxes which generated dynamically. So let's get started with it.
Step 1:
In this article we will pull some matching records from the database for our auto-complete. So first let's create a table called Tbl_SampleNames using the following script.
Create Table Tbl_SampleNames
(
NameId Bigint Primary Key Identity(1,1),
Name Varchar(100)
)
After creating the table, insert some values in the table.
Step 2:
Next we need to create one Generic Handler class which we will use to pull the names from database. So add one Generic Handler class and simply modify it's ProcessRequest like below.
string prefixText = context.Request.QueryString["q"];
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
{
conn.ConnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["sqlcn"].ConnectionString;
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
cmd.CommandText = "select Name from Tbl_SampleNames where " +
"Name like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
conn.Open();
using (System.Data.SqlClient.SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["Name"])
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
Thr above code contains only the stuff to pull the matching data in our table.
Step 3:
Next we have to design our user interface. Now you need to get some jQuery and css so first download jQuery UI from jQuery.com and add the following given files to your application. As well add the links in the Head section of your ASP.Net page and write the script for auto-complete.
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#article input:text').each(function () {
$(this).autocomplete("Handler.ashx");
})
});
</script>
In the above code we have given links to some .js and .css file as well one script which specifies the control id on our page which should be contains textboxes and calls our Handler.ashx.
Step 4:
Next we have to design our form with one default textbox. So write the following markup in your page body section.

sravan dPosted Jun 5, 2013, 12:59 AM
Nice one