Combobox search only items that match the typed

Asked

Viewed 1,277 times

1

In a User Registration Form, I have a combobox Civil Status Registry (which loads data from an SQL table), when writing to combobox the system needs to go searching the data and presenting only those that match the typed.

For example, type in combo Only then it will present only, Single, if I type Vi will just show the Widower and so on. I know that in the example quoted this will not be very useful, but I will use for city, state, etc.

I’m doing it this way:

In Form I have the following code:

private void carregaComboEstadoCivil()
{
    ProfissionalController profissional = new ProfissionalController();
    ProfissionalController.carregaComboEstadoCivil(cbxEstadoCivil);

    cbxEstadoCivil.KeyPress += new KeyPressEventHandler(cbxEstadoCivil_KeyPress);
}

Professional Class Controller I have the following:

public void carregaComboEstadoCivil(ComboBox combo)
{
    //Essa parte do código carrega os dados do SQL na combo.
    FuncionsDAL carrega = new FuncionsDAL();
    DataTable tabela = carrega.listaEstadoCivil();

    DataRow linha = tabela.NewRow();

    combo.DropDownStyle = ComboBoxStyle.DropDown;
    combo.AutoCompleteMode = AutoCompleteMode.Suggest;
    combo.DataSource = tabela;
    combo.DisplayMember = "Descricao";
    combo.ValueMember = "ID";
    combo.Update();
    linha["ID"] = 0;
    linha["Descricao"] = "Selecione...";
    tabela.Rows.InsertAt(linha, 0);
 }

Event of KeyPress:

private void cbxEstadoCivil_KeyPress(object sender, KeyPressEventArgs e)
{
    cbxEstadoCivil.DroppedDown = true;
}
  • My impression or you typed twice the same thing?

  • Jeferson, where I typed twice the same thing?

  • Read your question you’ll see.

  • Yeah, I’m all set!

1 answer

2


You just need to change the property DropDownStyle for DropDown, then change the properties AutoCompleteMode for anything other than None and AutoCompleteSource for ListItems.

Applying in your code:

public void carregaComboEstadoCivil(ComboBox combo)
{
    //Essa parte do código carrega os dados do SQL na combo.
    FuncionsDAL carrega = new FuncionsDAL();
    DataTable tabela = carrega.listaEstadoCivil();

    DataRow linha = tabela.NewRow();

    combo.DropDownStyle = ComboBoxStyle.DropDown;
    combo.AutoCompleteMode = AutoCompleteMode.Suggest;
    combo.AutoCompleteSource = AutoCompleteSource.ListItems; //Adicione essa linha
    combo.DataSource = tabela;
    combo.DisplayMember = "Descricao";
    combo.ValueMember = "ID";
    combo.Update();
    linha["ID"] = 0;
    linha["Descricao"] = "Selecione...";
    tabela.Rows.InsertAt(linha, 0);
 }
  • then if I change my method loadCivil(Combobox combo) Changing the line: combo.Autocompletemode = Autocompletemode.Suggest; to: combo.Autocompletemode = Autocompletemode.Listitems; it will work?

  • No. I’ll edit the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.