Intellisense in a Windows Forms Textbox
Recently I came across a problem of implementing a intellisense kind of feature in a normal text box in which the user will type some text in a textbox and keep getting intellisense help to complete the current word.
Basically it was typing of TableName and corresponding columns.
What ultimately was decided was that on typing of space (’ ‘) we will show intellisense with Table names and on typing of dot (’.') we will show corresponding column names.
Basics for Intellisense feature
- You require a TextBox Control to behave as your base editor.
- You require a ListBox Control to put all your items used for word completion.
- You require a method to get the point (Co-ordinates)of the current text being typed in the TextBox.
I guess you are good to get the first two items of the above list. The code for the last item is as follows:
private Point GetPoint(TextBox textBoxControl)
{
Graphics graphics = Graphics.FromHwnd(textBoxControl.Handle);
SizeF size = graphics.MeasureString(textBoxControl.Text.Substring(0,
textBoxControl.SelectionStart), textBoxControl.Font);
Point coord = new Point((int)size.Width + textBoxControl.Location.X,
(int)size.Height + textBoxControl.Location.Y);
return coord;
}
Then you can use this as follows
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
switch(e.KeyChar)
{
case '.':
listBox.Location = GetPoint(textBox);
listBox.Visible = true;
break;
}
}
And you are ready with the basic intellisense
Add these two methods as well
//to add an item to Textbox once your press tab in your listBox
private void listBox_Leave(object sender, EventArgs e)
{
textBox.Text += listBox1.SelectedItem.ToString();
textBox.SelectionStart = textBox.Text.Length;
}
//To start selecting the items once your press up / down arrows
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
listBox.Focus();
}
}


