Iam using AutoCompleteMode to my textbox. It will append the Bank names to my textbox. So when I started typing with the first leter all the Bank names with first lettre will come to dropdownlist to my textbox. Now my question is If user try to entre the data which is not im my dropdownlist, the user should not able to entre the text. So i want user to entr the existing bank names only. Iam using AutoCompleteCustomSource to the textbox for dropdown.
-
If the user is not allowed to enter new names, perhaps a [combobox](http://stackoverflow.com/questions/11780558/c-sharp-winforms-combobox-dynamic-autocomplete) is a more fitting solution. – CodeCaster Nov 26 '12 at 13:48
-
Easiest way to me would seem that you can just validate the value when the user submits the form. If it isn't a valid value, show the user an error (i.e. "Please enter a valid bank name"). – Mike Marynowski Nov 26 '12 at 13:57
-
Or just make it a dropdown...but I can see why certain situations make it better for the user to be able to type it in. – Mike Marynowski Nov 26 '12 at 13:58
-
SqlCommand cmd = new SqlCommand("select name from databasetable", con); SqlDataReader dr = cmd.ExecuteReader(); AutoCompleteStringCollection col = new AutoCompleteStringCollection(); while (dr.Read()) { col.Add(dr.GetString(0)); } textBox1.AutoCompleteCustomSource = col; – Naresh Nov 26 '12 at 13:59
2 Answers
try something like:
bool foundSome = false;
foreach (var bankName in col)
{
foundSome = bankName.StartsWith(textBox.text);
}
if (foundSome)
//Do some action
You can write this code in 'Validating' to preform for each char inserted in txtbox.

- 430
- 3
- 14
the best way to achieve your requierement is to use 1 textbox and 1 combobox. They both should point to the same collection.
Textbox will behave in autocomplete mode as you described. Once you type, combobox value will be set to first matching value from your collection. If no value matches - combobox value should be set to null or default data.
Combobox will store only corresponding data subset with no possibility to edit the chosen text.
Validation and data retrieval will be done from Combobox value.
Advantages of this approach:
- With large sets of data it will be easier for user to find what he/she needs.
- Lesser code to check if input value belongs to data set or to force belonging.
- No validation is needed.
Possible shortcomings:
- One more control at form.
- Logic to synchronize textbox's text and combobox collection should be implemented.

- 1,779
- 2
- 18
- 21