How to execute a method inside a textBox only if the user give enter?

1

I am trying to execute a method inside a textBox, only if the user gives enter. Check that I have to use Keypress, but I'm not able to apply. I want it when the user places the product code inside the textbox and enter, he can see the product. Code Below:

        private void textBox1_TextChanged(object sender, EventArgs e)
    {


        try
        {
            int Codigo = Convert.ToInt32(txtCodigo.Text);

            ProdutoDAL d = new ProdutoDAL();

            Produto p = d.ConsultarProduto(Codigo);

            if (p != null)
            {
                txtDescricao.Text = Convert.ToString(p.Estoque_descricao);
                txtReferencia.Text = Convert.ToString(p.Estoque_referencia);
                txtComplemento.Text = Convert.ToString(p.Estoque_descricao2);
                txtCodBarras.Text = Convert.ToString(p.Estoque_codbarras);
                txtCustoMedio.Text = Convert.ToString(p.Estoque_customedio);
                txtValorAVista.Text = Convert.ToString(p.Estoque_avista);
                txtValorTabela.Text = Convert.ToString(p.Estoque_tabela);
                txtValorPromocao.Text = Convert.ToString(p.Estoque_promocao);
                txtValorComDesconto.Text = Convert.ToString(p.Estoque_desconto);
                txtLinha.Text = Convert.ToString(p.Estoque_linha);
                txtSetor.Text = Convert.ToString(p.Estoque_setor);
                txtfigura.Text = Convert.ToString(p.Estoque_figura);
                txtMarca.Text = Convert.ToString(p.Estoque_marca);
            }
            else
            {
                MessageBox.Show("PRODUTO NAO CADASTRADO");

            }


        }
        catch (Exception ex)
        {

            throw new Exception("ERRO AO CONSULTAR PRODUTO" + ex.Message);
        }

    }
    
asked by anonymous 26.03.2015 / 04:54

1 answer

1

If you have to be only when you use the Enter key you can use the following:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // Seu codigo aqui
    }
}

Here, the event KeyDown will be triggered as soon as the user loads Enter (the event KeyPress expects the user to press and release).

If on the other hand it is always that the user completes the action of filling textbox :

private void textBox1_Validated(object sender, System.EventArgs e)
{

}

Here, the event Validated will be triggered when the content of textbox is validated.

Normally there is no validation by default, but if you want to add your own logic (see if the product code is correct for example) you can do so using the Validating (occurs when the control loses focus but before exiting the control itself).

    
26.03.2015 / 08:34