user682417 user682417 - 26 days ago 7
C# Question

search box with database

I am using C#.net Windows form , and I need to create a search textbox which will display combo box values (similar to google search);
The values displayed in the combo box will be values from the SQL 2005 database (example the user is searching on FirstName, the combobox will display all firstnames, which get filtered as the user types in more letters.... if user is searching on LastName, the combo box displays all LastName values in the database.. etc)

Any ideas how to go about this task?

Answer

This is a solution from the web that does do what you desire but have the negative effect to load everything from the start instead of doing small queries.

List<string> namesCollection = new List<string>();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = 'Connexion String or From File'
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select distinct [Name] from [Names] order by [Name] asc";
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
   while (dReader.Read())
   namesCollection.Add(dReader["Name"].ToString());
}
dReader.Close();

txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;