Why can not I call object cta1 instantiated in btnCriarConta_Click?

0

Why can not I call object cta1 instantiated in btnCriarConta_Click ?

namespace proj3 {
   public partial class conta : System.Web.UI.Page {
      protected void Page_Load(object sender, EventArgs e) {
      }
      protected void btnCriarConta_Click(object sender, EventArgs e) {
         try {
            decimal saldo = decimal.Parse(txtSaldo.Text);
            ContaBancaria cta1 = new ContaBancaria(1, saldo);
            Session.Add("conta", cta1);
            msgGeral.Text = "Conta criada com sucesso.";
         }catch (Exception ex){
         }
      }
      protected void btnDebitar_Click(object sender, EventArgs e) {
         try {
            cta1.debitar(decimal.Parse(txtSaldo.Text));
         } catch (Exception ex) {
         }
      }
      protected void btnCreditar_Click(object sender, EventArgs e)
      {
         try {
         }catch (Exception ex) {
         }
      }
   }
}
    
asked by anonymous 15.12.2017 / 16:57

2 answers

1

The snippet that code you added is not javascript, I think it's C #.

You can not access cta1 because of the scope, the variable only exists inside the body of the btnCriarConta_Click method.

In order to use the object within btnDebitar_Click you can get it through Session using the "account" key since after creating the ContaBancaria you save it in the user session.

Another solution that I'm not sure if it suits your case would be to set the account as a property of class conta and access that property in btnCriarConta_Click and btnDebitar_Click .

    
15.12.2017 / 17:48
0

Because the variable was created (therefore, it is limited) to the scope of the function.

That is, the variable cta1 is created in btnCriarConta_Click and only accessible from this function (after its declaration).

On the other hand, you are saving the object (variable content) in session state.

Basically, what is missing is to declare a variable of the same type in the desired function to get the object saved in the session, and then call the desired method.

protected void btnDebitar_Click(object sender, EventArgs e) 
{
     try 
     {
        ContaBancaria cta1 = (ContaBancaria) Session["conta"]; // Aqui!
        cta1.debitar(decimal.Parse(txtSaldo.Text));
     } 
     catch (Exception ex) 
     {
     }
}
    
15.12.2017 / 21:20