Search in the ComboBox only items that match the digits

1

In a User Registration Form, I have a% c_of% Civil Status Register (which loads the data from a SQL table), when writing to combobox the system needs to search the data and only present the ones that match with the typed one.

For example, I type in the So combo so it will only show Single if I type Vi Widow and so on. I know that in the example mentioned this will not be very useful, but I will use it 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);
 }

combobox event:

private void cbxEstadoCivil_KeyPress(object sender, KeyPressEventArgs e)
{
    cbxEstadoCivil.DroppedDown = true;
}
    
asked by anonymous 25.09.2015 / 16:39

1 answer

2

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

Applying to 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);
 }
    
25.09.2015 / 16:46