I want to have a textbox control that suggests and append values from a database in a Windows application with C# 2008 and LINQ.
I do it with a combobox but I can't do it with a textbox.
How do I do it?
AutoCompleteCustomSource is helpful for TextBox controls in which string sources like URLs, addresses etc. will be frequently entered. AutoCompleteCustomSource property is perform to set the custom list of values. AutoCompleteMode property is perform to set how the auto-complete candidates are displayed.
Append displays first value of the suggestion appended or selected in the TextBox, other values can be navigated using arrow keys. SuggestAppend displays suggested values as dropdown and first value appended in the TextBox. AutoCompleteSource property sets the source for auto complete data.
Turn on autocompletions: From the control panel, select the search engine you want to edit. Click Search features from the menu on the left and then click the Autocomplete tab. Click on the slider to set Enable autocomplete to On.
This might not be the best way to do things, but should work:
this.textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; private void textBox1_TextChanged(object sender, EventArgs e) { TextBox t = sender as TextBox; if (t != null) { //say you want to do a search when user types 3 or more chars if (t.Text.Length >= 3) { //SuggestStrings will have the logic to return array of strings either from cache/db string[] arr = SuggestStrings(t.Text); AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); collection.AddRange(arr); this.textBox1.AutoCompleteCustomSource = collection; } } }
Check out the AutoCompleteSource
, AutoCompleteCustomSource
and AutoCompleteMode
properties.
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
col.Add("Foo");
col.Add("Bar");
textBox1.AutoCompleteCustomSource = col;
Note that the designer allows you to do that without writing any code...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With