简体   繁体   中英

C# Accessing the same instance of a child form from 2 methods in the parent form

So far i have this code that i want to use to be able to call the same function in the child form.

Parent Form Code:

FormGame frmGame; // i put this here so that in the second function it doesnt complain about frmGame not being set.
    public void CreateGame(string Level) // this function is called first
    {
        FormGame frmGame = new FormGame(this); // i need both functions to be able to access this instance of the child form
        frmGame.SetLevel(Level); // sets the text of a label in the child form
        frmGame.Show();
    }

    public void UpdateGame(string Level) // then this function is called second 
    {
        frmGame.SetLevel(Level); // to update the same label as set in the first method
    }

the problem with this code is that while yes it doesn't come up with any errors when just sitting there but when debugging it when the second function is called it cant find the instance of FormGame that was set in the first function so frmGame is null.

I have tried:

  1. Pulling the whole form initializing statement outside both functions like this
    FormGame frmGame = new FormGame(this);
    but it doesnt like "this" not being inside a function and removing it from that line then removes the errors when running but then the label never changes when told to
  2. what is shown in the code at the top
  3. Having
    FormGame frmGame = new FormGame(this); At the top line inside of both of the functions but that just resets the form back to the initial one every time I try update it
  4. Tried using Refresh() in the second function and inside the child form after the label text gets changed but to no avail.
  5. And a few more but they were way off what i feel is correct.

    So my goal is to be able to create the form in the first function and set the label on it and then when the second function is called with a new string I want to be able to update that same label without closing the open form.

Your code creates a new instance of FormGame , whose scope is only inside that function. In no way does this affect the frmGame variable you defined outside of the method.

FormGame frmGame = new FormGame(this);

To avoid getting an error when you call UpdateGame , don't define a new variable inside the method.

public void CreateGame(string Level)
{
   frmGame = new FormGame(this);  // use the class-level field
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM