Sreenath Ganga
Sreenath Ganga

Reputation: 736

sorting values in combobox by typing

I have a combobox that is filled with data field JobCode from database. There are 1000s of jobcode and when the user needs to select one jobcode he has to scroll down through all the jobcodes in the combobox. Can I do it in such a way that if the user types some letter of jobcode it will show the jobcodes which start with that letter in the combobox at the top of list so the user can select easily. For example, like adding some code in keypressevent in combobox.

The user must still choose from jobcodes in the list, not keep partially or incorrectly entered data that will cause wrong data entry at insert and update time.

public void jobcomboboxload()
{
       OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
       oleDbConnection1.Open();
       OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobcode from  jobcodemastertable", oleDbConnection1);
       OleDbDataReader reader = oleDbCommand1.ExecuteReader();
       DataTable dt = new DataTable();
       dt.Columns.Add("jobpk", typeof(int));
       dt.Columns.Add("jobcode", typeof(string));
       dt.Load(reader);
       cmbjobcode.ValueMember = "jobpk";
       cmbjobcode.DisplayMember = "jobcode";
       cmbjobcode.DataSource = dt.DefaultView;

       oleDbConnection1.Close();
   }

jobcode is an unique field.

Upvotes: 0

Views: 509

Answers (2)

phadaphunk
phadaphunk

Reputation: 13303

Set your ComboBox AutoCompleteMode properties to Suggest AND AutoCompleteSource to ListItems or else you won't see the suggestion.

Like Steve said you can change your query and add ORDER BY on your request field to set the order in which you want them in your SELECT statement.

Hope this helps don't hesitate if you have any questions.

Upvotes: 1

Steve
Steve

Reputation: 216293

  • Use cmbjobcode.AutoCompleteMode = AutoCompleteMode.Suggest (or other values of the enum)
  • Use cmbjobcode.AutoCompleteSource = AutoCompleteSource.ListItems
  • Change your query including the clause ORDER BY on the field jobcode

Please, don't forget the using statement around your OleDbConnection, OleDbCommand and OleDbDataReader. This will assure the proper dispose of the before mentioned variables.

For the checking on incomplete values, you should add the Validating event and, in that event, check if the text entered is present in your strings.
The combobox has a method called FindStringExact() that can help.

Upvotes: 1

Related Questions