You are on page 1of 12

dale lane

fan of all things mobile, father of small girls, IBM code monkey, youth charity trustee…

« Charities Act 2006 implementation Fun with estate agents »


Twitter

Dale Lane Retweeted


AutoComplete with a .NETCF ComboBox
Winchester SciCentr
.NET Compact Framework doesn’t support auto-complete in text entry @WinSciCentre
controls. I didn’t realise that until I wanted it for a Form I was throwing
THE ULTIMATE STEM
together tonight, but there you go.
SCHOOL TRIP IS HERE!
So, in the spirit of Hack Day (which I’m still gutted to have missed!) I had Schools are invited to
a quick stab at throwing together something myself. explore science and take a
guided mission through
Read on to see what I mean, and how I did it. (And to tell me a better
way to do it!) space , as part of
Winchester Science Centre's
What is available
What am I reading?
»
To start with, a quick recap on what is provided, because you can get
some things a bit similar:

» a drop down list of strings to choose from – (using a ComboBox with a


DropDownStyle of DropDownList)
» clicking on the control with the stylus provides a scrollable list to
choose from
» pressing a key on the keyboard will cycle through all items in the
list which begin with that first letter (if there are 20 words See other books I've read recently

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
beginning with ‘T’, you need to press T fourteen times to get the Grace and Faith
fourteen item in the list)

» a drop down list of strings to choose from, allowing new items not
already on the list to be entered – (using a ComboBox with a
DropDownStyle of DropDown)
» clicking on the drop-down arrow with the stylus provides a
scrollable list to choose from

» using the keyboard allows new entries to be entered, ignoring the


list
Search
So what do I want?
Pages
I want:
» About this blog

» a drop-down list that I can choose from with the stylus


Archives
» to be able to type in new items not on the list » April 2018
» January 2018
» to be able to type in the start of items on the list, and have auto-
» October 2017
complete fill in the rest of the item for me (without needing to open
» August 2017
the list) » July 2017
» April 2017
Why do I want it? » February 2017
» November 2016
All of my PDAs have a full QWERTY keyboard. (Look at Treos – still one of » October 2016
the best examples of interfaces that can be used with one hand). Typing » August 2016
the first couple of letters of something is much quicker than getting out » July 2016
your stylus when filling in a form. If there are 20 words beginning with ‘T’, » June 2016
pressing T then O is a quicker way to pick the item of the list which » February 2016
begins TO. » May 2015
» April 2015
» January 2015
How have I done it?
» December 2014
» November 2014
Badly
» October 2014
» September 2014
It is a bit of a hack… I created a custom UserControl that contains both a
» August 2014
ComboBox (to give me the drop-down list) with a TextBox directly in front
» July 2014
of it (to give me the free-form text editing space).
» June 2014
» May 2014
I made the TextBox slightly narrower than the ComboBox behind it, so
» April 2014
that the drop-down arrow is still visible.
» February 2014
» January 2014

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
» December 2013
» November 2013
» August 2013
» June 2013
» May 2013
» April 2013
» February 2013
» December 2012
» November 2012
Why this way? » September 2012
» August 2012
I needed to be able to show the difference between the bit of the text » June 2012
that has been typed in manually, and the bit of the text that was provided » May 2012
by auto-complete. (Otherwise, the interface is too unclear – a user » April 2012
wouldn’t know where their next key-press would go). » March 2012
» February 2012
This is normally done by highlighting the auto-completed text. For » January 2012
example, after typing “app”… » December 2011
» November 2011
» October 2011
» September 2011
» June 2011
» May 2011
» April 2011
TextBox lets you programmatically alter selected text – with attributes » February 2011
SelectionStart, SelectionLength and so on. But it doesn’t have a » December 2010
drop-down list. » November 2010
ComboBox doesn’t let you programmatically alter selected text – it » October 2010
doesn’t have any of the Selection... attributes. » September 2010
» August 2010
So I figured that the quickest and easiest way to get the best of both » July 2010
worlds would be to have both. » June 2010
» May 2010
» April 2010
The code
» March 2010
» February 2010
Fairly straight-forward, but here ya go.
» January 2010
Download it here, but here is the interesting bit… » December 2009
» November 2009
using System; » October 2009
using System.Text; » September 2009
using System.Windows.Forms; » August 2009
» July 2009
namespace AutoComplete » June 2009
{ » May 2009

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
/* » April 2009
* AutoComplete » March 2009
* » February 2009
* a text box which allows free-form entry of text » January 2009
* whilst also providing auto-complete from a given » December 2008
* list of strings » November 2008
* » October 2008
* an item can be selected from the list either by: » September 2008
* a) choosing from the drop-down combobox list » August 2008
* b) typing enough characters of the start of the » July 2008
* desired item to uniquely identify it » June 2008
* » May 2008
* To use in a form: » April 2008
* 1) Drag onto a Form Designer using Visual Studio, » March 2008
* using the Form Designer to resize/place the » February 2008
* box » January 2008
* 2) Use SetItems to provide the list of strings used » December 2007
* to match for auto-complete » November 2007
* 3) Use AddItem to add any additional strings » October 2007
*/ » September 2007
public partial class AutoCompleteTextBox : UserControl » August 2007
{ » July 2007
// stores the items that are used for auto-complete » June 2007
private string[] comboBoxItems = new string[0]; » May 2007
» April 2007
public AutoCompleteTextBox() » March 2007
{ » February 2007
InitializeComponent(); » January 2007
» December 2006
// if the user uses the ComboBox to choose an item, » November 2006
// handle this by mirroring it in the TextBox » October 2006
» September 2006
innerComboBox.SelectedValueChanged += new EventHandler(innerComboBox_SelectedValueChanged);

// if the user uses the TextBox to enter text, Categories


// handle this with our home-made autocomplete code below
» blog
innerTextBox.KeyPress += new KeyPressEventHandler(innerTextBox_KeyPress);
» charity
} » code
» ibm
// provide the array of strings to use for auto-complete matches
» kids
// » misc
// it will replace any previous list provided » politics
public void SetItems(string[] items) » school
{ » tech
comboBoxItems = items; » unsorted
» web

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Array.Sort(comboBoxItems); Links
» my CV
innerComboBox.Items.Clear(); » my diary
» my links
for (int i = 0; i < comboBoxItems.Length; i++) » my online profiles
{ » my photos
innerComboBox.Items.Add(comboBoxItems[i]); » where am i?
}
} Disclaimer
// add an item to the array of strings used for auto-complete matches
The postings on this site are my own
public void AddItem(string newitem) and don't necessarily represent the
positions, strategies or opinions of
{
IBM or SYA.
string[] newitems = new string[comboBoxItems.Length + 1];

Array.Copy(comboBoxItems, newitems, comboBoxItems.Length);

newitems[comboBoxItems.Length] = newitem;

SetItems(newitems);
}
// clear the list of strings used for auto-complete matches
public void ClearItems()
{
comboBoxItems = new string[0];
innerComboBox.Items.Clear();
}

// the user has used the ComboBox to select one of the possible
// auto-complete matches
//
// handle this by mirroring it in the textbox
void innerComboBox_SelectedValueChanged(object sender, EventArgs e)
{
innerTextBox.Text = innerComboBox.Text;
}

// the user has used the TextBox to modify the text


//
// we look at what has been typed so far, and if it matches
// anything in the list, we fill the text box with it
//
// text which has been 'auto-complete-d' (rather than typed)
// is denoted by being selected
void innerTextBox_KeyPress(object sender, KeyPressEventArgs e)
{

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
// this is where we store any match found in the auto-complete list
string match = null;

// what has been typed so far?


int cursorLocation = innerTextBox.SelectionStart;
string typedSoFar = innerTextBox.Text.Substring(0, cursorLocation);

// what is the user adding now?


switch (e.KeyChar)
{
// BACKSPACE - the user is deleting a character - so we shink
// our 'typedSoFar' string by one character
case (char)Keys.Back:
if (cursorLocation > 0)
{
cursorLocation -= 1;
typedSoFar = innerTextBox.Text.Substring(0, cursorLocation);
}
break;

// DELETE - do nothing, allowing the 'delete' keystroke to delete


// the selected text provided from a previous auto-complete
case (char)Keys.Delete:
break;

// RETURN - do nothing - swallow this keystroke


case (char)Keys.Return:
// don't do anything else
goto key_handle_complete;

// OTHERWISE - assume we have a alphanumeric keystroke which


// we add to the string typed-so-far
default:
typedSoFar += e.KeyChar;
cursorLocation += 1;
break;
}

// look for a match in the auto-complete list


for (int i = 0; i < comboBoxItems.Length; i++)
{
if (comboBoxItems[i].StartsWith(typedSoFar, StringComparison.CurrentCultureIgnoreCase))
{
match = comboBoxItems[i];

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
// we want first match - once found, break out
break;
}
}

// was a match found?

if (match == null)
{
// user has typed something not already in the list
innerTextBox.Text = typedSoFar;
innerTextBox.SelectionStart = typedSoFar.Length;
innerTextBox.SelectionLength = 0;
}
else
{
// user has typed text which matches the start of something
// in the provided auto-complete list

// display this match, and highlight the portion of it which


// was not actually typed by the user
innerTextBox.Text = match;
innerTextBox.SelectionStart = cursorLocation;
innerTextBox.SelectionLength = innerTextBox.Text.Length - innerTextBox.SelectionStart;

innerComboBox.SelectedItem = match;
}

// COMPLETE - finally, prevent key-press being handled by text box itself


key_handle_complete: e.Handled = true;
}
}
}

Will it work?

Probably?

Not sure if it will handle a user typing too much too fast, so some sort of
synchronisation might need to be looked at before this gets used in
earnest. But it is enough for my needs tonight, and seemed to do the
trick.

There’s gotta be a better way though! Any suggestions?

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
This entry was posted on Sunday, June 17th, 2007 at 11:16 pm and is filed under code.
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and
pings are currently closed.

12 Responses to “AutoComplete with a .NETCF ComboBox”

Hari Das Kumaran says:


Friday 28th September 2007 at 5:53 am

Hi,

I tried to open your code in VS.NET 2.0 but was contineously getting the error
“Error retreiving information from user database. Platform not found”.

I wonder why it is coming. I am using Windows XP as OS.

dale says:
Friday 28th September 2007 at 9:46 am

@Hari

It sounds like you don’t have the Windows Mobile SDK installed. This is for
.NETCF (Compact Framework) – which is to say the version of .NET for mobile
devices, not “regular” .NET.

Tzahi Kupfer says:


Thursday 8th November 2007 at 7:30 am

(Hari)
I had the same problem
In order to fix it I opended (with notepad) a “csproj” file of some (Well)
working project of mine, and copied the line
In my case it was:

3C41C503-53EF-4c2a-8DD4-A8217CAD115E
Then I opened “AutoComplete.csproj” and repalce the original line.

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
now it seems working.

Tzahi.

Tzahi Kupfer says:


Thursday 8th November 2007 at 7:35 am

(Hari)

This editor eliminates “tags” so I’m resending it,
this time without consider “[” as “<“.
Tzahi.

I had the same problem
In order to fix it I opended (with notepad) a “csproj” file of some (Well)
working project of mine, and copied the “PlatformID” line
In my case it was:

[PlatformID] 3C41C503-53EF-4c2a-8DD4-A8217CAD115E [/PlatformID]


Then I opened “AutoComplete.csproj” and repalce the original “PLatformID”
line.

now it seems working.

Tzahi.

Bobby Beckner says:


Wednesday 30th April 2008 at 12:02 pm

This is exactly what I was looking for! A resounding “thank you!”

dale says:
Wednesday 30th April 2008 at 1:34 pm

@Tzahi Kupfer – sounds like you hacked the project so that what was
originally a project targeted for the Windows Mobile platform could be built for
the Windows desktop platform.

It’s not what I’d originally intended (I think the ComboBox you get with
standard desktop .NET already gives you AutoComplete anyway!) but I’m glad
you found it useful anyway.

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
dale says:
Wednesday 30th April 2008 at 1:34 pm

@Bobby Beckner – Glad it helped – thanks for taking the time to comment!
It’s that sort of thing that makes it worth keep sharing this sort of stuff.

Ricky says:
Friday 2nd May 2008 at 10:03 am

Hi Dale.

I ended up doing much the same as you and I want to take it to the next step
– have it do data binding.

For the life of me I can’t get the text, selectedindex or selectedvalue to show
on the bindings at design time.

Also need to expose DataSource and DisplayMember so in the designer I can


make it do what a normal combobox does.

I can do this if I inherit Combobox rather than Usercontrol but then I can’t get
the text box to receive the key input.

Any ideas?

regards, Ricky

Niru says:
Tuesday 30th September 2008 at 9:00 pm

I used your code inside innerTextBox_KeyPress … I had to tweak it a little bit


by handling the case (typedSoFar != string.Empty) => this is needed as the
StartsWith method in string returns true when typedSoFar is empty and
match automatically becomes the first item in the comboBox.

Thanks for sharing

Lars Ole Avery Simonsen says:


Tuesday 25th November 2008 at 3:14 pm

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Have a look at my ComboBox-derivation here:
http://larsole.com/files/autocomplete-combobox.cs

It uses interop (pieced that together from various other blog postings) to do
what it does. It has no textfield mojo other than what is already in a standard
combobox.

I can even use it with objects other than strings (objects with a ToString()
override) in the Items collection.

Vassili says:
Thursday 14th October 2010 at 11:22 pm

Excellent, exactly what I was looking for. Thanks a lot for sharing.
Just some small recommendation: it is not very intuitive what is going on
when the user tries to delete selected text (actually nothing in your sample).
To delete selected text, here is the change:

case (char)Keys.Back:
if (innerTextBox.SelectionLength > 0 || cursorLocation > 0)
{
if (innerTextBox.SelectionLength == 0)
{
cursorLocation -= 1;
}
typedSoFar = innerTextBox.Text.Substring(0, cursorLocation);
innerTextBox.Text = innerTextBox.Text.Remove(cursorLocation,
Math.Max(innerTextBox.SelectionLength, 1));
innerTextBox.SelectionStart = typedSoFar.Length;
innerTextBox.SelectionLength = 0;

goto key_handle_complete;
} break;

Also, on my mobile pressing dot “.” was triggering Keys.Delete … so i had to


comment out the corresponding handling.

inyu says:
Tuesday 22nd February 2011 at 5:13 pm

Does anybody have this translated to VB.NET ?

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
dale lane is proudly powered by WordPress
Entries (RSS) and Comments (RSS).

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD

You might also like