Help - C# how to update combobox? type autocomplete

Asked

Viewed 1,236 times

5

First I am developing a C# system and using Sql Server as a database.

I would like to accomplish the following task: When something is typed in the combobox I update the itself, by means of a search in the bank, example:

I type A in the combobox and load it with the return of the selecte.

Other Example: Similar to google search, American, extra and etc. Style an autocomplete, and it is necessary to use the combobox, because in it I have to bring the name in the display and the code in the value of the combobox.

Like a autocomplete, but I need it to be a combobox because in it I bring together a code.

I programmed it this way:

exe:

comboBox.DataSource = dataTable;
comboBox.DisplayMember = "Nome";
comboBox.ValueMember = "codigo;

Inside the combobox Textchanged.

select is right and the datatable is right, but I’m having the following problem the combobox takes the first line that returns and doesn’t let me keep typing, nor does it change to bottom record (OBS: Returns more than one line) nor at least it shows the list, simply "lock" in the first line.

I do not know if you have to configure some property of the combobox or perform in a specific event ...

First I had made an autocomplete in a textbox, it works but I can’t get the option code is selected.

And I didn’t want to load the combobox with all the records. So it’s not something heavy.

More specifically I’m making a form related to sale, and I’m researching the customer this way. I don’t even know if it has like.

I am grateful for any suggestion.

Updating --

combobox textChanged codex

    private void cmbNome_Cliente_TextChanged(object sender, EventArgs e)
    {
        Cliente cliente = new Cliente();
        cliente.Nome = cmbNome_Cliente.Text;
        cliente.Razao_social = cmbNome_Cliente.Text;


        cmbNome_Cliente.DataSource = cliente.CarregaClienteNome(); "Isso retorna um dataTable"
        cmbNome_Cliente.DisplayMember = "Nome - Razao Social";
        cmbNome_Cliente.ValueMember = "Código";
    }

//Search Customer for Combobox by name ##updated

    public DataTable CarregaClienteNome()
    {
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();

        try
        {
            conn.Open();
            cmd.Connection = conn;

            cmd.CommandText = "select top(5) cli.cod_cliente as Código, ";
            cmd.CommandText += "(case when pes.cod_tipo_pessoa = 1 then Nome else Razao_Social end) as 'Nome - Razao Social' ";
            cmd.CommandText += "from tab_Pessoa pes ";
            cmd.CommandText += "inner join tab_Cliente cli on pes.cod_pessoa = cli.cod_pessoa ";
            cmd.CommandText += "where pes.nome like '" + Nome + "%' or pes.razao_social like '" + Razao_social + "%'";
            cmd.CommandText += " order by 'Nome - Razao Social'";

            da.SelectCommand = cmd;
            da.Fill(dt);
            cmd.ExecuteNonQuery();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            conn.Close();
        }

        return dt;
    }

//Autocomplete - test I’ve done with autocomplete in a textbox, it’s working. However I can’t get the code

private void txtTeste_TextChanged(object sender, EventArgs e)
    {
        Cliente cliente = new Cliente();

        cliente.Nome = txtTeste.Text;
        cliente.Razao_social = txtTeste.Text;

        DataTable dt = new DataTable();

        var source = new AutoCompleteStringCollection();

        dt =cliente.CarregaClienteNome();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            source.Add(dt.Rows[i][1].ToString());
        }


        txtTeste.AutoCompleteCustomSource = source;            

    }
  • shows the complete combobox "Textchanged" code

  • Why not use a textbox with combobox, write in one, show in another?

  • Another detail, I had a similar problem when I filled some fields that changed the combobox, it was not updated... Try placing comboBox1.Datasource = null; before assigning the return of the function to it and if you are using a Datatable in the Chargename() function put nameDataTabledtResult.Clear(); before filling it. and at the end, under cmbNome_Cliente.Valuemember = "cod_client"; put comboBox1.Refresh();

  • It would be interesting to put the code of Payload();

  • I saw that you were having trouble getting the selection of the autocomplete, I can help you. I think it would be better with the textobox and the autocomplete. What do you think?

  • The autocomplete has a following problem I can’t get the code of the selected client.

  • The first time I did it with autocomplete in the textbox, the logic is that but I can’t get the code.

  • Marconi, if you have any way to get the code using autocomplete, that would be very helpful. I updated the post with a test I had done using the autocomplete in a textbox.

  • Why not use the Jquery Ui autocomplete. Look at the example I put up. If you need help, you can add me to skype. Marconi.barroso92

Show 4 more comments

1 answer

3

At friend’s request @Luisfelipemicaidejesus I will put an example using autoComplete.

 <asp:TextBox ID="txtPesquisarHipotese" runat="server" Width="300px"></asp:TextBox>
 <asp:HiddenField ID="hdfPesquisarHipotese" runat="server" Value="" />

txtPesquisarHipothesis ==> Textbox that will put Autocomplete.

hdfPesquisarHipothesis ==> hiden that will hide the User Selection.

When I use the function select i take the value that the user selected and save in Hiddenfield.

If you need more details, specify in the comments that I edit the answer.

$(function () {
    $("#<%=txtPesquisarHipotese.ClientID%>").autocomplete(
                    {
                        source: function (request, response) {
                            $.ajax({
                                url: '<%=ResolveUrl("../ws/AutoComplete.asmx/GetEscopo")%>',
                                data: JSON.stringify({
                                    'prefixText': request.term
                                }),
                                dataType: "json",
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                success: function (data) {
                                    response($.map(data.d, function (item) {
                                        return {
                                            label: item.split('#')[1],
                                            val: item.split('#')[0]
                                        }
                                    }))
                                },
                                error: function (response) {
                                    alert(response.responseText);
                                },
                                failure: function (response) {
                                    alert(response.responseText);
                                }
                            });
                        },
                        select: function (e, i) {
                            $("#<%=hdfPesquisarHipotese.ClientID%>").val(i.item.val);
                        },
                        minLength: 1
                    });
});

Code inside my file . asmx Note: If you want you can use the url to access a Webmethod inside your page.

    [WebMethod]
    public string[] GetEscopo(string prefixText)
    {
        SqlConnection conn = null;
        List<string> resultado = new List<string>();

        try
        {
            using (conn = new SqlConnection(Conexao))
            {
                SqlCommand cmd = new SqlCommand("select Escopo from Escopos where Escopos.Escopo like @prefixText group by Escopo order by Escopo", conn);
                SqlParameter param = new SqlParameter();
                cmd.Parameters.Add("@prefixText", SqlDbType.VarChar);
                cmd.Parameters["@prefixText"].Value = "%" + prefixText + "%";
                conn.Open();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        resultado.Add(dr["Escopo"].ToString());
                    }
                    dr.Close();
                }
            }
        }
        catch { }
        finally
        {
            if (conn != null)
            {
                conn.Close();
            }
        }
        return resultado.ToArray();
    }
  • @Luis Felipe Micai de Jesus It worked?

Browser other questions tagged

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