[英]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. 这段代码的问题是,虽然是的,但是当它坐在那里时并没有出现任何错误,但是在调用第二个函数时对其进行调试时,它找不到在第一个函数中设置的FormGame实例,因此frmGame为null 。
I have tried: 我努力了:
Your code creates a new instance of FormGame
, whose scope is only inside that function. 您的代码创建一个FormGame
的新实例,其范围仅在该函数内部。 In no way does this affect the frmGame
variable you defined outside of the method. 这绝不会影响您在方法外部定义的frmGame
变量。
FormGame frmGame = new FormGame(this);
To avoid getting an error when you call UpdateGame
, don't define a new variable inside the method. 为避免在调用UpdateGame
时UpdateGame
,请不要在方法内部定义新变量。
public void CreateGame(string Level)
{
frmGame = new FormGame(this); // use the class-level field
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.