using System.Windows.Forms;
using System;

namespace Northwind
{
	/// <summary>
	/// Summary description for AutoCompleteComboBox.
	/// </summary>
	public class AutoCompleteComboBox : ComboBox
	{
		public AutoCompleteComboBox()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		protected override void OnKeyUp(KeyEventArgs e) 
		{

			switch(e.KeyCode)
			{
				case Keys.Back:
				case Keys.Delete:
				{
					//user is deleting a character (or more);
					//make sure no item is selected in the list
					this.SelectedIndex = -1;
					return;
				}
				case Keys.Tab:
				case Keys.Enter:

				case Keys.Left:
				case Keys.Right:
				case Keys.Down:
				case Keys.Up:
				case Keys.ControlKey:
				case Keys.ShiftKey:
				case Keys.Escape:
					//Ignore these..
					return;
			}

			string typedText = this.Text;

			if(typedText.Length > 0)
			{
				if(this.Items.Count != 0)
				{//Make sure combo isn't empty
					for(int counter=0;counter<this.Items.Count;counter++)
					{
						//Compare the typed in text to the part of the item
						//to see if they match...
						string itemToCompare = this.Items[counter].ToString();
						if(typedText.Length <= itemToCompare.Length)
						{
							string compareText = typedText +
								itemToCompare.Substring(typedText.Length, 
								itemToCompare.Length - typedText.Length);
							if(0==String.Compare(itemToCompare, compareText, true))
							{
								//we have a match, select the latter part of the
								//Text so that the user can type-over it
								this.SelectedIndex = counter;
								this.Select(typedText.Length, 
									itemToCompare.Length - typedText.Length);
								break;
							}
						}
					}
				}
			}		 
		}
	}
}