Why can’t I call cta1 instantiated object in btnCriarConta_Click?

Asked

Viewed 33 times

0

Why can’t 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) {
         }
      }
   }
}
  • Where is Javascript in this code?

2 answers

1

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

You can’t access it cta1 because of the scope, the variable exists only within the body of the method btnCriarConta_Click.

To be able to use the object inside btnDebitar_Click you can get it through the Session using the "account" key since after creating the ContaBancaria you save it in the user session.

Another solution that I’m not sure fits your case would be to define the account as a class property conta and access this property on btnCriarConta_Click and btnDebitar_Click.

0

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

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

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

Basically, what is missing is declaring a variable of the same type in the desired function to get the saved object in the session, and then calling 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) 
     {
     }
}

Browser other questions tagged

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