简体   繁体   中英

How to force a user to take a suggested entry into a ComboBox?

I want a user to select a value from a ComboBox. Entries have to be suggested at user's text input.

Do I have to use events to enforce a System.Windows.Forms.ComboBox to contain a value from its own DataSource ?

Example: Entries have to be suggested to the user... If I write "CO", the combo should suggest "CONGO" and "COLOMBIA", but only one of those values should be entered by the user. The user should not introduce "COfdfgdfg" or any random string.

Thanks!

将组合框的样式设置为ComboBoxStyle.DropDownList

You have to use combobox.autocompletemode to get the names liek Congo,congress when the user enter the text like "CO"

you can your own datasource to comboBox1.AutoCompleteSource

 this.comboBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.comboBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(113, 192);
 this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 20);

Then populate the combox items source with objects like, that override the ToString method

public class POCLRO
{
  public int ID { get; set; }
  public string Name { get; set; }

  public override string ToString()
  {
    return Name;
  }
}

Edit: You have to do validation on text entered by the user in combobox , if the user selects the drop down item suggested by auto completemode the validation returns true else it returns false ...

Do something like below ...

Create a KeyDown event handler for the combobox and check for an Enter key. Note that after the user hits enter the text in the combobox is selected (as in, selected as if you were doing a cut or copy operation) and focus remains in the combobox.

If enter was pressed call a validation function that will do whatever you feel necessary if the value entered is equal with name that was stored in database...

You can call this same function in a Leave event handler to prevent the user from leaving the combobox until a valid selection is made.

 private void ComboBox_KeyDown(object sender, KeyEventArgs e)
 {
    if (e.KeyCode == Keys.Enter)
    {
        ValidateSelection();
    }
 }

 private  bool validation()
 {
   // do validation here 
 }
private void ComboBox_Leave(object sender, EventArgs e)
{
    if(!ValidateSelection())
    {
        ComboBox.Focus();
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM