0

Estou precisando atualizar o textbox troco quando o textbox receber valor do cliente, for preenchido, utilizo essa função dentro do textbox receber valor do cliente no evento TextChanged:

 protected void txtvalordocliente_TextChanged(object sender, EventArgs e)
    {
        if (txtvalordocliente.Text == "")
        {
            txtvalordocliente.Text = "0";
            decimal troco = decimal.Parse(txtvalordocliente.Text.Replace("R$", "")) - decimal.Parse(txtvalorareceber.Text.Replace("R$", ""));
            txttroco.Text = troco.ToString();
        }
        else
        {
            decimal troco = decimal.Parse(txtvalordocliente.Text.Replace("R$", "")) - decimal.Parse(txtvalorareceber.Text.Replace("R$", ""));
            txttroco.Text = troco.ToString();
        }
    }

E aqui está o meu código em html, porém ou ele funciona uma vez ou outra ou ele não funciona, não consigo resolver.

 <asp:UpdatePanel ID="UpdatePanel12" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional">
                                <ContentTemplate>
                                    <asp:Label ID="Label44" runat="server" Text="Forma de Pagamento"></asp:Label>
                                    <br />
                                    <asp:DropDownList ID="cbformapg" runat="server">
                                        <asp:ListItem>DINHEIRO</asp:ListItem>
                                        <asp:ListItem>CHEQUE</asp:ListItem>
                                        <asp:ListItem>CARTÃO</asp:ListItem>
                                        <asp:ListItem>BOLETO</asp:ListItem>
                                        <asp:ListItem>DEPÓSITO</asp:ListItem>
                                    </asp:DropDownList>
                                    <br />
                                    <asp:Label ID="Label46" runat="server" Text="Valor Do Cliente"></asp:Label>
                                    <br />
                                    <asp:TextBox ID="txtvalordocliente" runat="server" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$" AutoPostBack="True" OnTextChanged="txtvalordocliente_TextChanged"></asp:TextBox>
                                    <br />
                                    <asp:Label ID="Label47" runat="server" Text="Valor a Receber"></asp:Label>
                                    <br />
                                    <asp:TextBox ID="txtvalorareceber" runat="server"  onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$" AutoPostBack="False" OnTextChanged="txtvalorareceber_TextChanged"></asp:TextBox>
                                    <br />
                                    <asp:Label ID="Label48" runat="server" Text="Troco"></asp:Label>
                                    <br />
                                    <asp:TextBox ID="txttroco" runat="server"  onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$" AutoPostBack="True"></asp:TextBox>
                                    <br />
                                </ContentTemplate>
                            </asp:UpdatePanel>

Evento Load:

 if (!IsPostBack)
            {
                Session["contador"] = 0;
                CarregaTaxa();
                CarregaContas();
                btnReceber.Visible = false;
                btnExcluir.Visible = false;
                CarregaReceitas();
                idconta();
                CarregaServicos();
                txtObs.InnerText = cbreceita.SelectedItem + "(" + cbplanos.SelectedItem + ")" + " - " + txtPessoa.Text;
                txtValorIncluir.Enabled = true;
                Valor();
                txtVencimentoIncluir.Text = DateTime.Now.ToString("dd/MM/yyyy");
                DateTime data = DateTime.Now;
                Data.Value = data.ToString();
                SqlConnection conexao = clsdb.AbreBanco();
                SqlDataAdapter da = new SqlDataAdapter("select c.id,case WHEN s.descricao is null THEN 'VENDA DE PRODUTO'else s.descricao END AS Modalidade, convert(date,c.vencimento,103) as Vencimento,c.Observacao , c.valor_pago, c.valor, quitado, p.nome, p.id from dbo.contas_receber as c left join servicos as s  on s.id = c.servico_id left join pessoa as p on p.id = c.pessoa_id where vencimento >= (convert (char(10), getdate(),103)) and vencimento <= (convert (char(10), getdate(),103))  order by vencimento asc", conexao);

                ds = new DataSet();
                da.Fill(ds, "contas_receber");

                GridView1.DataSource = ds.Tables["contas_receber"];
                GridView1.DataBind();
                cbPesquisa.Text = "Pessoa";
                if (cbPesquisa.Text == "Pessoa")
                {
                    txtDataInicial.Visible = false;
                    txtDataFinal.Visible = false;
                    txtPesquisa.Visible = true;
                }
                if (cbPesquisa.Text == "Plano")
                {
                    txtDataInicial.Visible = true;
                    txtDataFinal.Visible = true;
                    txtPesquisa.Visible = true;
                }
                if (cbPesquisa.Text == "Vencimento")
                {
                    txtDataInicial.Visible = true;
                    txtDataFinal.Visible = true;
                    txtPesquisa.Visible = false;
                }

                if (cbPesquisa.Text == "Recebimento")
                {
                    txtDataInicial.Visible = true;
                    txtDataFinal.Visible = true;
                    txtPesquisa.Visible = false;
                }

                GridPessoa();
                GridComprador();
                CarregaProdutos();
                if (cbreceita.SelectedItem.ToString() != "VENDA DE PRODUTOS")
                {
                    idconta();
                    CarregaServicos();
                    txtObs.InnerText = cbreceita.SelectedItem + "(" + cbplanos.SelectedItem + ")" + " - " + txtPessoa.Text;
                    txtValorIncluir.Enabled = true;
                    Valor();
                    Button4.Visible = false;
                    Label22.Visible = true;
                    cbplanos.Visible = true;
                    txtValorIncluir.Enabled = true;
                    Button3.Enabled = true;
                }
                if (cbreceita.SelectedItem.ToString() == "VENDA DE PRODUTOS")
                {
                    txtObs.InnerText = cbreceita.SelectedItem + "(" + cbplanos.SelectedItem + ")" + " - " + txtPessoa.Text;
                    cbplanos.Visible = false;
                    txtValorIncluir.Enabled = false;
                    Button3.Enabled = false;
                    Button4.Visible = true;
                    Label22.Visible = false;
                }
                UpQuantidade.Text = "1";
                txtDescontoAdd.Text = "0,00";
                CarregaValorProduto();
                SqlConnection conConexao6 = clsdb.AbreBanco();
                SqlCommand cmd6 = new SqlCommand("SELECT valor_venda,id FROM produto where nome='" + cbProdutoAdd.SelectedItem + "'", conConexao6);
                SqlDataReader dr6 = cmd6.ExecuteReader();

                if (dr6.HasRows == true)
                {
                    if (dr6.Read())
                    {
                        txtValorAdd.Text = dr6[0].ToString();
                        txtValorFinalAdd.Text = dr6[0].ToString();
                        txtidprodutoAdd.Text = (dr6[1].ToString());
                    }
                }        
            }

9
  • Adiciona o código de todo o seu evento e também o page load.
    – Aline
    7/06/2017 às 13:01
  • Adicionei o do evento, na página load, não tem relacionado a este código, até tentei colocar dentro do if (!IsPostBack) porém não funcionou.
    – Mariana
    7/06/2017 às 13:03
  • Adiciona o código do pageLoad, porque seu problema pode estar lá.
    – Aline
    7/06/2017 às 13:05
  • Adicionei Aline.
    – Mariana
    7/06/2017 às 13:08
  • Na verdade Aline, rs agora não está nem atualizando, tentei colocar updatepanel como sempre, autopostback como true de todos, porém nenhuma forma está funcionando agora.
    – Mariana
    7/06/2017 às 13:17

2 Respostas 2

1

Como você não quer o postback da página para atualizar o #txtTroco, uma sugestão é fazer esse processo no client, com js.

Vai precisar alterar seu código html para que os IDs dos elementos não alterem (ClientIDMode):

<asp:UpdatePanel ID="UpdatePanel12" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional">
    <ContentTemplate>
    <asp:Label ID="Label44" runat="server" Text="Forma de Pagamento">/asp:Label>
    <asp:DropDownList ID="cbformapg" runat="server">
        <asp:ListItem>DINHEIRO</asp:ListItem>
        <asp:ListItem>CHEQUE</asp:ListItem>
        <asp:ListItem>CARTÃO</asp:ListItem>
        <asp:ListItem>BOLETO</asp:ListItem>
         <asp:ListItem>DEPÓSITO</asp:ListItem>
    </asp:DropDownList>
    <asp:Label ID="Label46" runat="server" Text="Valor Do Cliente"></asp:Label>
    <asp:TextBox ID="txtvalordocliente" runat="server" ClientIDMode="Static" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$" onblur />                                        
    <asp:Label ID="Label47" runat="server" Text="Valor a Receber"></asp:Label>
    <asp:TextBox ID="txtvalorareceber" runat="server"  onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$"/>
    <asp:Label ID="Label48" runat="server" Text="Troco"></asp:Label>
    <asp:TextBox ID="txttroco" runat="server" ClientIDMode="Static" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$"/>
</ContentTemplate>
</asp:UpdatePanel>

e escrever um js, vou usar jquery:

<script>
    $(document).ready(function(){
        $(document).on("blur", "#txttroco", function(){
            var valorcliente = $("#txtvalordocliente").val();
            if(!valorcliente){
                valorcliente = 0;
            $("#txtroco").val(Number(valorcliente.replace("R$", "")) - Number($("#txtvalorareceber").val().replace("R$", "")));
        });
    });
    </script>
1

O problema, pode estar no entendimento da propriedade ChildrenAsTriggers.

Caso a propriedade estiver

ChildrenAsTriggers="false"

é necessário informar Triggers.

Portanto você tem 2 opções ou coloca a propriedade

ChildrenAsTriggers = true (default)

Ou adicionar Triggers, como no exemplo abaixo:

 <asp:UpdatePanel ID="UpdatePanel12" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Label ID="Label44" runat="server" Text="Forma de Pagamento"></asp:Label>
            <br />
            <asp:DropDownList ID="cbformapg" runat="server">
                <asp:ListItem>DINHEIRO</asp:ListItem>
                <asp:ListItem>CHEQUE</asp:ListItem>
                <asp:ListItem>CARTÃO</asp:ListItem>
                <asp:ListItem>BOLETO</asp:ListItem>
                <asp:ListItem>DEPÓSITO</asp:ListItem>
            </asp:DropDownList>
            <br />
            <asp:Label ID="Label46" runat="server" Text="Valor Do Cliente"></asp:Label>
            <br />
            <asp:TextBox ID="txtvalordocliente" runat="server" AutoPostBack="true" placeholder="R$" Text="0" OnTextChanged="txtvalordocliente_TextChanged"></asp:TextBox>
            <br />
            <asp:Label ID="Label47" runat="server" Text="Valor a Receber"></asp:Label>
            <br />
            <asp:TextBox ID="txtvalorareceber" runat="server" Text="500"></asp:TextBox>
            <br />
            <asp:Label ID="Label48" runat="server" Text="Troco"></asp:Label>
            <br />
            <asp:TextBox ID="txttroco" runat="server"></asp:TextBox>
            <br />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="txtvalordocliente" EventName="TextChanged" />
        </Triggers>
    </asp:UpdatePanel>

CodeBehind

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                txtvalorareceber.Text = "550";
        }
 protected void txtvalordocliente_TextChanged(object sender, EventArgs e)
        {
            decimal valorcliente = 0;
            decimal valorreceber = 0;
            decimal troco = 0;

            if (Decimal.TryParse(txtvalordocliente.Text, out valorcliente) && Decimal.TryParse(txtvalorareceber.Text, out valorreceber))
                troco = valorcliente - valorreceber;

            txttroco.Text = troco.ToString();
        }

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .