Click here to Skip to main content
12,634,651 members (25,899 online)
Click here to Skip to main content
Add your own
alternative version

Stats

255.5K views
5K downloads
81 bookmarked
Posted

A C# auto complete combo box

, 14 Apr 2003
Rate this:
Please Sign up or sign in to vote.
A C# implementation of an auto complete combo box, based on Chris Maunder's MFC code

Introduction

I had the need to create a combo box control that auto completes as the user types into it. I scoured the fantastic resources available at Code Project, and found a great example in MFC, by Chris Maunder.

My requirements were that I wanted to use completely managed code for my project, and, as Chris's control was written with MFC, I decided to roll my own, based on his. I have added an additional property to this control, which limits the control to the list of items.

All the magic of the control happens in the OnTextChanged event. The _inEditMode field is set in the OnKeyDown event, based on whether or not the backspace or delete key was pressed. If this field is true, then the code finds the partial string, selecting the portion that the user has already typed.

OnValidating is overridden to fire a NotInList event in the case that the LimitToList property is true, allowing the user to perform some action if the user enters some text that is not in the list of item.

OnNotInList is also provided as a protected virtual method so that derived classes may call the event handler without subscribing to receive its events.

The source code

using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace MattBerther.Controls
{
    public class AutoCompleteComboBox : System.Windows.Forms.ComboBox
    {
        public event System.ComponentModel.CancelEventHandler NotInList;

        private bool _limitToList = true;
        private bool _inEditMode = false;

        public AutoCompleteComboBox() : base()
        {
        }

        [Category("Behavior")]
        public bool LimitToList
        {
            get { return _limitToList; }
            set { _limitToList = value; }
        }

        protected virtual void 
            OnNotInList (System.ComponentModel.CancelEventArgs e)
        {
            if (NotInList != null)
            {
                NotInList(this, e);
            }
        }   

        protected override void OnTextChanged(System.EventArgs e)
        {
            if (_inEditMode)
            {
                string input = Text;
                int index = FindString(input);

                if (index >= 0)
                {
                    _inEditMode = false;
                    SelectedIndex = index;
                    _inEditMode = true;
                    Select(input.Length, Text.Length);
                }
            }

            base.OnTextChanged(e);
        }

        protected override void 
            OnValidating(System.ComponentModel.CancelEventArgs e)
        {
            if (this.LimitToList)
            {
                int pos = this.FindStringExact(this.Text);
        
                if (pos == -1)
                {
                    OnNotInList(e);
                }
                else
                {
                    this.SelectedIndex = pos;
                }
            }

            base.OnValidating(e);
        }

        protected override void 
            OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            _inEditMode = 
                (e.KeyCode != Keys.Back && e.KeyCode != Keys.Delete);
            base.OnKeyDown(e);
        }
    }
}

Using this control

Use this control in the same manner as you would a regular System.Windows.Forms.ComboBox. Add it to your form, via the designer or programmatically as detailed below.

protected override void OnLoad(System.EventArgs e)
{
    base.OnLoad(e);

    MattBerther.Controls.AutoCompleteComboBox cb = new 
        MattBerther.Controls.AutoCompleteComboBox();

    cb.Items.Add("Apples");
    cb.Items.Add("Oranges");
    cb.Items.Add("Grapefruits");

    cb.LimitToList = true;
    cb.NotInList += new CancelEventHandler(combobox_NotInList);
    this.Controls.Add(cb);
}

private void combobox_NotInList(object sender, CancelEventArgs e)
{
    MessageBox.Show("You entered a value that was not 
        consistent with the list provided. Please try again.");
    e.Cancel = true;
}

Many thanks again to Chris Maunder for providing an excellent starting point for implementing my own auto complete combo box in completely managed code.

History

  • 1.0 - 04.15.2003 - First release version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Matt Berther
Web Developer
United States United States
I am a 31 year old software developer from Boise, Idaho. I have been working with computers since approximately age 12, when my 6th grade teacher got me hooked. My parents got me a Commodore 64 for Christmas that year, and it's been downhill ever since. Wink | ;)

I have taught myself software development, beginning with Microsoft's Visual Basic 4.0. Approximately 5 years ago, I was given an opportunity to work in the tech field for a company called HealthCast. HealthCast's web-based technology solutions manage and control access to applications and patient information stored in legacy systems, client-server applications, or web solutions.

I left HealthCast in February 2003, to pursue a fantastic opportunity with Healthwise. Healthwise provides content to organizations and informs people to help them make better health decisions, creating Prescription-Strength Information™ tools that doctors trust and consumers use.

I have been working with the .NET framework since version 1.0, beta 2 and have not looked back since. Currently, I am most intrigued by the uses of the .NET framework and XML to create distributed, reusable applications.

You may also be interested in...

Comments and Discussions

 
Questionhow to set the postion & size of the combobox Pin
Rahulostwal9-Apr-15 1:27
memberRahulostwal9-Apr-15 1:27 
Questionnice control, help with a VB version Pin
chj12424-Jun-11 9:25
memberchj12424-Jun-11 9:25 
AnswerRe: nice control, help with a VB version Pin
kerrymanam17-Sep-14 22:20
memberkerrymanam17-Sep-14 22:20 
GeneralThere's a bug Pin
Shukra10-Aug-10 17:52
memberShukra10-Aug-10 17:52 
Generalhi Pin
`christah18-Jul-10 17:15
member`christah18-Jul-10 17:15 
GeneralThis is a bit too buggy and overcomplicated... Follow Hanan Nachmany alternative! Pin
leoseccia13-Nov-07 23:46
memberleoseccia13-Nov-07 23:46 
GeneralAutoCompleteComboBox at design time Pin
dgpdgp15-Aug-06 23:10
memberdgpdgp15-Aug-06 23:10 
GeneralGreat work Pin
Lars Hackstein7-Jul-04 15:05
sussLars Hackstein7-Jul-04 15:05 
GeneralA simple and elegant alternative Pin
Hanan Nachmany6-Jun-04 4:58
memberHanan Nachmany6-Jun-04 4:58 
GeneralRe: A simple and elegant alternative Pin
Matt Berther4-Sep-04 11:05
memberMatt Berther4-Sep-04 11:05 
GeneralRe: A simple and elegant alternative Pin
Tracey22-Sep-04 7:08
sussTracey22-Sep-04 7:08 
GeneralRe: A simple and elegant alternative Pin
Rob.5-Dec-04 12:55
memberRob.5-Dec-04 12:55 
GeneralRe: A simple and elegant alternative Pin
baranils29-Feb-08 14:29
memberbaranils29-Feb-08 14:29 
GeneralIgnores first character Pin
aneedham@sucden.co.uk2-Dec-03 6:56
memberaneedham@sucden.co.uk2-Dec-03 6:56 
GeneralRe: Ignores first character Pin
timothy d burgess20-Apr-04 6:39
membertimothy d burgess20-Apr-04 6:39 
GeneralComboBox Error Pin
Donny Lai1-Sep-03 19:23
memberDonny Lai1-Sep-03 19:23 
GeneralRe: ComboBox Error Pin
Valdis Iljuconoks8-Sep-03 10:46
sussValdis Iljuconoks8-Sep-03 10:46 
GeneralRe: ComboBox Error Pin
Matt Berther10-Sep-03 17:08
memberMatt Berther10-Sep-03 17:08 
GeneralRe: ComboBox Error Pin
Donny Lai10-Sep-03 17:45
memberDonny Lai10-Sep-03 17:45 
GeneralRe: ComboBox Error Pin
Matt Berther10-Sep-03 18:42
memberMatt Berther10-Sep-03 18:42 
GeneralRe: ComboBox Error Pin
Donny Lai10-Sep-03 18:43
memberDonny Lai10-Sep-03 18:43 
GeneralRe: ComboBox Error Pin
Matt Berther16-Sep-03 11:47
memberMatt Berther16-Sep-03 11:47 
GeneralRe: ComboBox Error Pin
Matt Berther18-Sep-03 22:34
memberMatt Berther18-Sep-03 22:34 
GeneralRe: ComboBox Error Pin
Donny Lai20-May-04 18:54
memberDonny Lai20-May-04 18:54 
GeneralRe: ComboBox Error Pin
PrasertHong12-Jul-06 2:02
memberPrasertHong12-Jul-06 2:02 
GeneralDatasource Pin
Fabricio30-Aug-03 14:35
memberFabricio30-Aug-03 14:35 
GeneralRe: Datasource Pin
Anonymous8-Sep-03 10:27
sussAnonymous8-Sep-03 10:27 
GeneralRe: Datasource Pin
Fabricio9-Sep-03 3:37
memberFabricio9-Sep-03 3:37 
GeneralRe: Datasource - kind works Pin
Rescue_Ranger10-Sep-03 12:07
memberRescue_Ranger10-Sep-03 12:07 
GeneralRe: Datasource - kind works Pin
Matt Berther10-Sep-03 16:58
memberMatt Berther10-Sep-03 16:58 
GeneralRe: Datasource - No Sorry Pin
Rescue_Ranger11-Sep-03 2:25
memberRescue_Ranger11-Sep-03 2:25 
GeneralRe: Datasource - No Sorry Pin
Matt Berther16-Sep-03 11:53
memberMatt Berther16-Sep-03 11:53 
GeneralRe: Datasource - No Sorry Pin
daviding1-Oct-03 19:02
memberdaviding1-Oct-03 19:02 
GeneralRe: Datasource - No Sorry Pin
Yuqing Zhu7-Nov-03 3:52
sussYuqing Zhu7-Nov-03 3:52 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161208.2 | Last Updated 15 Apr 2003
Article Copyright 2003 by Matt Berther
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid