簡體   English   中英

C#從父窗體的2個方法訪問子窗體的相同實例

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

到目前為止,我已經有了此代碼,希望能夠以子窗體形式調用相同的函數。

家長表格代碼:

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
    }

這段代碼的問題是,雖然是的,但是當它坐在那里時並沒有出現任何錯誤,但是在調用第二個函數時對其進行調試時,它找不到在第一個函數中設置的FormGame實例,因此frmGame為null 。

我努力了:

  1. 像這樣在兩個函數之外拉出整個表單初始化語句
    FormGame frmGame =新的FormGame(this);
    但是它不喜歡“ this”不在函數內部並從該行中刪除,然后刪除運行時的錯誤,但是當告訴
  2. 頂部代碼中顯示的內容

  3. FormGame frmGame =新的FormGame(this); 在這兩個函數的頂行,但是每次我嘗試更新表單時,它都會將表單重置為初始表單
  4. 標簽文本更改但無濟於事后,在第二個函數中以及子窗體內部使用Refresh()進行了嘗試。
  5. 還有一些,但它們與我認為正確的相去甚遠。

    因此,我的目標是能夠在第一個函數中創建表單並在其上設置標簽,然后在使用新字符串調用第二個函數時,我希望能夠在不關閉打開的表單的情況下更新同一標簽。

您的代碼創建一個FormGame的新實例,其范圍僅在該函數內部。 這絕不會影響您在方法外部定義的frmGame變量。

FormGame frmGame = new FormGame(this);

為避免在調用UpdateGameUpdateGame ,請不要在方法內部定義新變量。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM