Guys,I am designing an autocomplete textbox in c#.I have done it,but i need to add some control with it.Consider google search textbox,where a list appears and user can select from the list.My problem is when you type in textbox a list apeears below it,but u need to select an item by mouse,it can't be done by keyboard.Moreover,the list doesn't disappear after selection,this is another problem.I used key event here,but it seems not working or i'm doing wrong.I need to add those controls as google textbox.Any suggestion?? Below is my code..
List<string> nameList;
nameList = new List<string>
{
"A0-Word","B0-Word","C0-Word",
"A1-Word","B1-Word","C1-Word",
"B2-Word","C2-Word",
"C3-Word",
};
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
string typedString = textBox1.Text;
List<string> autoList = new List<string>();
autoList.Clear();
foreach (string item in nameList)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (item.StartsWith(typedString))
{
autoList.Add(item);
}
}
}
if (autoList.Count > 0)
{
listBox1.ItemsSource = autoList;
listBox1.Visibility = Visibility.Visible;
}
else if (textBox1.Text.Equals(""))
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
else
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.ItemsSource != null)
{
listBox1.Visibility = Visibility.Collapsed;
if (listBox1.SelectedIndex != -1)
{
textBox1.Text = listBox1.SelectedItem.ToString();
}
listBox1.KeyDown += new KeyEventHandler(listBox1_KeyDown);
}
}
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (ReferenceEquals(sender, listBox1))
{
if (e.Key == Key.Enter)
{
Close();
}
else if (e.Key == Key.Escape)
{
Close();
}
if (e.Key == Key.Down)
{
e.Handled = true;
listBox1.Items.MoveCurrentToNext();
}
if (e.Key == Key.Up)
{
e.Handled = true;
listBox1.Items.MoveCurrentToPrevious();
}
}
}