বুধবার, ৩০ নভেম্বর, ২০১১

Autosuggest Textbox for WPF

In this post i will share to everyone how to make an auto suggest TextBox in wpf like GOOGLE Textbox.
For this i create a grid whose first row contains a textbox and the second row contains a Listbox. Now, when the textbox gets the focus and its text changes due to the user’s input then fill up the listbox.
Here is the XAML code

1<Grid>
2        <TextBox Height="23" HorizontalAlignment="Left" Margin="111,46,0,0" Name="txtAutoSuggestName" VerticalAlignment="Top" Width="161" PreviewKeyDown="txtAutoSuggestName_PreviewKeyDown" TextChanged="txtAutoSuggestName_TextChanged" />
3        <ListBox Height="Auto" HorizontalAlignment="Left" Margin="111,69,0,0" Name="listBoxSuggestion" VerticalAlignment="Top" Width="161" Visibility="Hidden" PreviewKeyDown="listBoxSuggestion_PreviewKeyDown" KeyDown="listBoxSuggestion_KeyDown" />
4    </Grid>

Now this is CS code for glorious effect in textbox
01private void txtAutoSuggestName_TextChanged(object sender, TextChangedEventArgs e)
02       {
03           listBoxSuggestion.Items.Clear();
04           if (txtAutoSuggestName.Text != "")
05           {
06               List<Customer> namelist = CustomerGatewayObj.listShow(txtAutoSuggestName.Text);
07               if (namelist.Count > 0)
08               {
09                   listBoxSuggestion.Visibility = Visibility.Visible;
10                   foreach (var obj in namelist)
11                   {
12                       listBoxSuggestion.Items.Add(obj.id);
13                   }
14               }
15           }
16           else
17           {
18               listBoxSuggestion.Visibility = Visibility.Hidden;
19           }
20       }
21 
22       private void txtAutoSuggestName_PreviewKeyDown(object sender, KeyEventArgs e)
23       {
24           if (e.Key == Key.Down)
25           {
26               listBoxSuggestion.Focus();
27           }
28       }
29 
30 
31       private void listBoxSuggestion_PreviewKeyDown(object sender, KeyEventArgs e)
32       {
33           if (listBoxSuggestion.SelectedIndex == 0 && e.Key == Key.Up)
34           {
35               txtAutoSuggestName.Focus();
36           }
37       }
38 
39       private void listBoxSuggestion_KeyDown(object sender, KeyEventArgs e)
40       {
41           if (listBoxSuggestion.SelectedIndex > -1)
42           {
43               if (e.Key == Key.Enter)
44               {
45                   txtAutoSuggestName.Text = listBoxSuggestion.SelectedItem.ToString();
46               }
47           }
48       }

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন