Creating Dynamic Textboxes With Auto Complete


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.

<div class="article" id="article">
<h3><span>Dynamic Textboxes With Autocomplete</span></h3>           
<table>
<
tr>
<
td>
 <asp:Panel ID="Panel1" runat="server" BorderStyle="None">
     <asp:TextBox ID="txtdefault" runat="server"></asp:TextBox><br />

    </asp:Panel>
</td>
</
tr>
<
tr>
<
td>
<
asp:Panel ID="Panel2" runat="server"></asp:Panel>
</td>
</
tr>
</
table> 
</div>

Step 5:

Still we are ready with static design now we will write some cs code for generating dynamic textboxes so write following code in your page code behind.

Panel pnlTextBox;
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //Create a Dynamic Panel
        pnlTextBox = Panel1;

        pnlTextBox.BorderWidth = 1;

        pnlTextBox.Width = 300;

        //Create a LinkDynamic Button to Add TextBoxes
        LinkButton btnAddtxt = new LinkButton();
        btnAddtxt.ID = "btnAddTxt";
        btnAddtxt.ForeColor = Color.Black;
        btnAddtxt.Text = "Add More TextBoxes";
        btnAddtxt.Click += new System.EventHandler(btnAdd_Click);
        Panel2.Controls.Add(btnAddtxt);

        //Recreate Controls
        RecreateControls("txtDynamic", "TextBox");
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        int cnt = FindOccurence("txtDynamic");
        CreateTextBox("txtDynamic-" + Convert.ToString(cnt + 1));
    }
    private int FindOccurence(string substr)
    {
        string reqstr = Request.Form.ToString();
        return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
    }
    private void RecreateControls(string ctrlPrefix, string ctrlType)
    {
        string[] ctrls = Request.Form.ToString().Split('&');
        int cnt = FindOccurence(ctrlPrefix);
        if (cnt > 0)
        {
            for (int k = 1; k <= cnt; k++)
            {
                for (int i = 0; i < ctrls.Length; i++)
                {
                    if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
                    {
                        string ctrlID = ctrls[i].Split('=')[0];
 
                        if (ctrlType == "TextBox")
                        {
                            CreateTextBox(ctrlID);
                        }
                        break;
                    }
                }
            }
        }
    }

    private void CreateTextBox(string ID)
    {
        TextBox txt = new TextBox();
        txt.ID = ID;
        txt.AutoPostBack = true;
        pnlTextBox.Controls.Add(txt);
        Literal lt = new Literal();
        lt.Text = "<br />";
        pnlTextBox.Controls.Add(lt);
    }

In the above code we are creating textboxes dynamically with a linkbutton which is also created dynamically. Now run the application and see the result.

Conclusion:

Using simple jQuery we can provide the easy auto-complete in our application.

Up Next
    Ebook Download
    View all
    Learn
    View all