Home > front end >  How to refer to 1 instance of winform instead of making a new Instance
How to refer to 1 instance of winform instead of making a new Instance

Time:12-14

Regarding to my previous question, It is very helpful to know what I am doing wrong but still I cannot make it work with only making one instance, this is the current code so far, It is supposed to change the value of a textbox in one form without making a new form.

Form 2:

private void btnAward2_Click(object sender, EventArgs e)
{
    display.RevealItems(2);
}

private void btnAward3_Click(object sender, EventArgs e)
{
    display.RevealItems(3);
}

private void btnAward4_Click(object sender, EventArgs e)
{
    display.RevealItems(4);
}

Form 1:

public void RevealItems(int ItemNo)
{
    Items zItems = JsonSerializer.Deserialize<Items>(File.ReadAllText(FilePath()));
    switch (ItemNo)
    {
        case 1:
            Item1.Text = zItems.ItemArray[0];
            Score1.Text = zItems.ScoreArray[0];
            InitializeComponent();
            break;
        case 2:
            Item2.Text = zItems.ItemArray[1];
            Score2.Text = zItems.ScoreArray[1];
            InitializeComponent();
            break;
        case 3:
            Item3.Text = zItems.ItemArray[2];
            Score3.Text = zItems.ScoreArray[2];
            InitializeComponent();
            break;
        case 4:
            Item4.Text = zItems.ItemArray[3];
            Score4.Text = zItems.ScoreArray[3];
            InitializeComponent();
            break;
        case 5:
            Item5.Text = zItems.ItemArray[4];
            Score5.Text = zItems.ScoreArray[4];
            InitializeComponent();
            break;
        case 6:
            Item6.Text = zItems.ItemArray[6];
            Score6.Text = zItems.ScoreArray[6];
            InitializeComponent();
            break;
    }
}

I tried many answers in the internet but It didn't work.

CodePudding user response:

Remember that forms are just classes. You track instances of forms like you track instances of any other class: by storing a reference to the instance in a variable. For a given form on the screen, you need to know what variables you used for the form when first calling the .Show() or .ShowDialog() methods, and make sure to use the same variable (or a copy of the variable) at later points where you refer to the form.

In a Winforms project, this means going all the way back to the startup of the program, because there are different ways in the Visual Studio project you might set the program to start and show the initial form. We don't have that information in the question, so this is as far as I can take you at the moment.

  • Related