Erica Erica - 2 years ago 65
C# Question

Creating an object instance with a button click

I am currently creating a very simple bank account program: The user enters the accountholder name, account number and beginning balance, then presses a "Continue" button to work with that account by making deposits and withdrawals. I wrote a separate

class with the required data members and methods. I've put the code for the creation of the BankAccount object in the
button click event

BankAccount currentAccount = new BankAccount(acctName, acctNum, beginningBalance);

But that seems to make it local to that method only, and
is not recognized when I'm programming the click event for the "Record Transactions" (deposits and withdrawals) button.

How and where should the creation of the BankAccount object be coded in order for it to be created when the "Continue" button is clicked and also recognized in the "Record Transactions" button click event? Please let me know if any clarification is needed, or if you need to see part or all of my code.

Answer Source

You need to declare the BankAccount object outside the click handler for it to remain in scope. You can instantiate it within the click handler, if that's what you need to do

The code below has not been tested to compile. It is only to give you an idea of what is required. The exact implementation and method signatures will differ based on whether you're working with Winforms or WPF

BankAccount account = null;

public void Continue_onClickHandler(EventArgs e) {
  account = new BankAccount();

public void RecordTransaction_onClickHandler(EventArgs e) {
  if (account == null) {
     throw new Exception("BankAccount has not been instantiated");

  // do whatever you need to do with account here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download