Click here to Skip to main content
13,351,896 members (64,794 online)
Click here to Skip to main content
Add your own
alternative version


14 bookmarked
Posted 20 Jan 2007

Converting zichun's auto-complete textbox control to a .NET ASCX user control

, 28 Mar 2008
Rate this:
Please Sign up or sign in to vote.
This article covers how I converted the JavaScript auto-complete textbox into a .NET user control which can have the items set easily and programmatically.


I had a requirement to be able to quickly record call history for a customer when they telephoned; which was to be implemented in a footer of a .NET master page; thus appear on every page of the website. Since there were over 500 customers in the system, a dropdown list would have been too large, and it would have been too complex to introduce some sort of search-engine in the footer of a master page.

I came across a CodeProject article written by zichun here. It also includes a demo which did exactly what I wanted; but was implemented in JavaScript and required the entries for the autocomplete dropdown to be pre-specified in script, which was not quite ideal for what I needed: a dynamic list of strings from a database.

This article looks at how I implemented this control as a .NET user control which can be drag-dropped onto any ASPX web form where it is needed and can have its items list dynamically and easily set programmatically.


Thank you to zichun of CodeProject for the original article referenced above. All the JavaScript code is his; and is excellent.


The first thing to do was to include the two JavaScript files in my project. For more information about these files, you can see the original article this was based on, here. I created an App_Javascript folder in the root of my project (just to follow the .NET naming convention) and included actb.js and common.js; both of which were written by zychun and I take no credit for.

Next, I created a /Controls folder and added into it a new .NET user control called AutoCompleteTextBox.ascx. The first thing to do was create the markup. All that was needed was simply a TextBox control (where the user will enter what they want to auto-complete) and a Literal which was used to output the script tags containing the items which would appear as auto-complete options. Thus, the content of AutoCompleteTextBox.ascx was:

<asp:TextBox id="txtTheTextbox" runat="server" />
<asp:Literal id="litTheJS" runat="server" />

The next thing to do was to write some code in Page_Init of this user control which wrote out references to common.js and actb.js in the head tag of the page if they did not exist already. This means that these references will only appear in pages which use this control, and they will never be accidentally missed out. To do this, I simply checked for the existence of a Literal in the page header; if it did not exist, then I created it and added it as follows:

Note that this relies on the files being in the App_Javascript folder in your application root, change as appropriate:

Protected Sub Page_Init(ByVal sender As Object, _
                        ByVal e As System.EventArgs) Handles Me.Init
    ' Register the JS which is needed (if it has not been added before):
    If IsNothing(Me.Page.Header.FindControl("litAutocompleteTextBoxSrc")) Then
        Dim lit As New Literal
        lit.ID = "litAutocompleteTextBoxSrc"
        lit.Text = vbCrLf + String.Format("<script language="'javascript'"" &_
            " type='text/javascript' src='{0}'></script>", _

        lit.Text += vbCrLf + String.Format("<script language="'javascript'"" &_
            " type='text/javascript' src='{0}'></script>", _

        lit.Text += vbCrLf

    End If
End Sub

With the .js files now included in the header tags of the rendered ASPX page, the next job was simply to provide two properties to get/set the text and the width of the TextBox control:

Public Property Text() As String
        Return Me.txtTheTextbox.Text
    End Get
    Set(ByVal value As String)
        Me.txtTheTextbox.Text = value
    End Set
End Property

Public Property Width() As Unit
        Return Me.txtTheTextbox.Width
    End Get
    Set(ByVal value As Unit)
        Me.txtTheTextbox.Width = value
    End Set
End Property

Now, I added a write-only property named Items which is an array of strings. I implemented this as WriteOnly because I wanted it to be possible to change or set the items at any time. However, I saw no real reason to ever need to read out the string array of items, so implemented this as write-only so that I would never try to read them and get confused as to why I got a null/empty string array!

The trick is that this property converts the string array object into a long string which the JavaScript uses as its items array. So, a string array containing the words apple, orange, and banana gets converted into the long string 'apple','orange','banana' including all the ' marks.

This long string is then stored into a ViewState variable which is used later when rendering out the JavaScript:

Public WriteOnly Property Items() As String()
    Set(ByVal value As String())
        Dim ItemsString As String = String.Empty

        For Each s As String In value
            ItemsString += "'" & s & "',"

        ' Remove the training comma
        ItemsString = ItemsString.Substring(0, ItemsString.Length - 1)

        ViewState("TheItems") = ItemsString
    End Set
End Property

And finally, my last trick is to set the contents of the literal we defined in the markup to be the javascript which is required to make the auto-complete dropdown list work. I did this in the Page_Load event of the control; and simply used the contents of the ViewState variable set using the .Items property created above. This also calls the actb function (defined in one of the JavaScript files) to "attach" the dropdown list to the TextBox using the TextBox's ClientID:

Protected Sub Page_Load(ByVal sender As Object, _
                        ByVal e As System.EventArgs) Handles Me.Load
    Me.litTheJS.Text = String.Format("<script type='text/javascript'> " &_
            "var customarray = new Array({1}); " &_
            "actb(document.getElementById('{0}'),customarray); </script>",
            Me.txtTheTextbox.ClientID, ViewState("TheItems"))
End Sub

And that's it! The control is now ready for use.

Using the Control

To use the control, simply add a reference to it in a page's markup (such as .aspx or .master) as you would any custom user control. (This can also be done by dragging the control from the Solution Explorer onto the page in Design view, and Visual Studio will automatically write the markup for you):

<%@ Register Src="~/Controls/AutoCompleteTextBox.ascx" 

    TagName="AutoCompleteTextBox" TagPrefix="bgs" %>

And then when you want the TextBox to appear:

<bgs:AutoCompleteTextBox ID="txtAutoComplete" runat="server" Width="300px"  />

Finally, all that is left is to set the .Items property of the control anywhere you like in code to set the auto-complete dropdown content of the box, and the rest of it just works, thanks to zichun's JavaScript:

Me.txtAutoComplete.Items = New String() {"Apple", "Orange", "Banana"}

Known Issues

I noticed that originally this worked perfectly when working on the web server machine, but failed when looking at the application on the server from a remote machine. However, Server.MapPath("~") returns a link to c:\inetpub\wwwroot\... - which obviously when connecting to the application remotely caused a JavaScript "object required" error because the remote machine had no such file - but worked perfectly on the server. The answer was to fix the path a bit in Page_Init of the control.


I would welcome any feedback on this control; although I cannot promise to be able to help with any queries. This works perfectly for my needs; and whilst I will try to help where I can, I am very busy at the moment!


I've said it a lot, but this control could not have been written without the JavaScript and article by zychun, here.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
United Kingdom United Kingdom
I graduated with a First class honours degree in Computer Science from the University of Salford in June 2006. Shortly after I graduated, I started my first job as a web developer in a small consultancy company in the North-West. I have since moved to a larger organisation in Manchester, which is a bit closer to my home.

My development is 99% ASP.NET based with the remaining 1% being ad-hoc console applications or Windows services, and although I prefer to develop in C# (just because I think it is cleaner), VB is what is used in the team.

You may also be interested in...


Comments and Discussions

GeneralSource fileq Pin
Agraha6-Apr-08 10:35
memberAgraha6-Apr-08 10:35 
GeneralRe: Source fileq Pin
bgs2648-Apr-08 5:32
memberbgs2648-Apr-08 5:32 
GeneralRe: Source fileq Pin
MGreville21-Apr-08 4:25
memberMGreville21-Apr-08 4:25 
QuestionCan it work Dynamically through Database Pin
manjots13-Jul-07 1:26
membermanjots13-Jul-07 1:26 
AnswerRe: Can it work Dynamically through Database Pin
sangram3607-Aug-08 10:20
membersangram3607-Aug-08 10:20 
GeneralGetting the txtTheTextbox value on a keypress postback to do a filter query Pin
timyee25-May-07 14:00
membertimyee25-May-07 14:00 
QuestionProblem when adding 2 controls in the same page Pin
dim_n23-May-07 2:40
memberdim_n23-May-07 2:40 
When I add 2 controls in the same page, the controls have the same list to autocomplete and not their own.

I have change the code of the page_load to:
Me.litTheJS.Text = String.Format(" var customarray_" & Me.ID & " = new Array({1}); var obj_" & Me.ID & " = actb(document.getElementById('{0}'),customarray_" & Me.ID & "); ", Me.txtTheTextbox.ClientID, ViewState("TheItems"))

therefore i create dynamically the name of the array, but i have the same list to both controls.

I of course have add 2 lists (1 for each control, a and b) in my project:
Me.a.Items = New String() {"Apple", "Orange", "Banana"}
Me.b.Items = New String() {"Earth", "Wind", "Fire"}

Can someone help me

thanks in advance

AnswerRe: Problem when adding 2 controls in the same page Pin
dimitrios_n23-May-07 2:58
memberdimitrios_n23-May-07 2:58 
GeneralProblem with Firefox Pin
K32130-Mar-07 4:19
memberK32130-Mar-07 4:19 
GeneralWorks very well! One change... Pin
diadexus27-Feb-07 10:13
memberdiadexus27-Feb-07 10:13 
GeneralViewState Pin
Member #270058926-Feb-07 3:20
memberMember #270058926-Feb-07 3:20 
GeneralPage.Header issue Pin
Craig_Muckleston6-Feb-07 0:45
memberCraig_Muckleston6-Feb-07 0:45 
GeneralRe: Page.Header issue Pin
bgs2646-Feb-07 0:46
memberbgs2646-Feb-07 0:46 
GeneralRe: Page.Header issue Pin
tanthuc20-May-07 5:53
membertanthuc20-May-07 5:53 
GeneralRe: Page.Header issue Pin
bgs26420-May-07 23:40
memberbgs26420-May-07 23:40 
GeneralRe: Page.Header issue Pin
tanthuc21-May-07 19:13
membertanthuc21-May-07 19:13 
GeneralRe: Page.Header issue Pin
bgs26421-May-07 22:17
memberbgs26421-May-07 22:17 
GeneralRe: Page.Header issue Pin
tanthuc21-May-07 19:54
membertanthuc21-May-07 19:54 
GeneralTrouble Using The Control Pin
ameyayashu260726-Jan-07 7:30
memberameyayashu260726-Jan-07 7:30 
GeneralRe: Trouble Using The Control Pin
bgs2644-Feb-07 1:18
memberbgs2644-Feb-07 1:18 
GeneralRe: Trouble Using The Control Pin
ameyayashu26074-Feb-07 18:22
memberameyayashu26074-Feb-07 18:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180111.1 | Last Updated 28 Mar 2008
Article Copyright 2007 by bgs264
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid