Help - C # how to update comboBox? autocomplete type

5

Firstly I'm developing a system in C # and using Sql Server as a database.

I would like to perform the following task: When something is typed in the comboBox I update myself, through a search in the database, example:

I type A in the comboBox and loads it with the return of the select.

Another example: Same as google search, american, extra, and so on. Style an autocomplete, it is necessary to use the comboBox, because in it I have to bring the name on the display and the code in the value of the comboBox.

Style an autocomplete, but I need it to be a comboBox because in it I bring a code together.

I've programmed it as follows:

exe:

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

Inside the TextChanged of the comboBox.

The select is right and the dataTable is correct, but I am having the following problem the comboBox takes the first line that returns and does not leave I continue typing, nor changes to low register (OBS: Returns more than one line) nor at least it shows the list, it simply "hangs" on the first line.

I do not know if it has to configure some property of the comboBox or perform in a specific event ...

Firstly I had done an autocomplete in a textBox, it works but I can not pick the code the option is selected for.

And I did not want to load the comboBox with all the records. So there's something heavy.

More specifically I'm doing a sales-related form, and I'm researching the client that way. I do not know if there's any way.

I'm grateful for any suggestions right now.

Update -

comboBox textChanged chord

    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";
    }

// Find Client for the ComboBox by the 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 that I did with autocomplete in a textBox, it is working. But I can not 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;            

    }
    
asked by anonymous 17.01.2015 / 10:22

1 answer

3

At the request of the friend @LuisFelipeMicaideJesus I'll put an example using autoComplete .

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

txtSearchHipotese == > Textbox that will put the AutoComplete.

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

When I use the select function, I get the value that the user selected and saved in HiddenField.

If you need more details, please 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 .asmx file Note: If you want you can use the url to access a WebMethod within 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();
    }
    
10.02.2015 / 13:37