0

The thing I am doing is that I have 2 forms. One form is named "Bank" and the second Form is named "Home".

In the form "bank" I want to have a variable that contains the value of how much money you have. I also want that variable to work in the "Home" form where there is a game that you can use the money.

Not sure how to define the variables so they can be used interchangeably and get updated. So how do I define them?

2 Answers2

0

You can pass a reference of form to the other form constructor so that you can reference the instance of the class. Let's say you have BankForm and HomeForm:

public class BankForm
{
    private HomeForm homeForm = null;

    public BankForm(HomeForm homeForm)
    {
        this.homeForm = homeForm;
    }

    private void OnButton1_Click(...)
    {
        this.homeForm. //here you can access properties of home form
    }

See: Fully access a control from another Form

Or if these values are global you can define as a static class to store kind of values:

static class Global
{
    private static string _money  = "";

    public static string Money
    {
        get { return _money; }
        set { _money = value; }
    }
}

See: C# - Winforms - Global Variables

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
0

It's not best practice, but you can define static variable in you Bank form (note that you can only have one Bank form this way).

More correct way is to create some other class (AccountService) that can get user's balance, and create instance of this class in both forms

maxc137
  • 2,291
  • 3
  • 20
  • 32