2011-11-30 176 views
1

我有2種形式:Form1和Form2。我用打開窗體2:如何在Form2中使用Form1中的變量?

Form2 newForm2 = new Form2(this); 

現在我要訪問從Form1中某些變量或方法,這些方法在公共設置,如:public int counter;

但是當我嘗試這從Form2的它給了我一個錯誤:

Error 4 'System.Windows.Forms.Form' does not contain a definition for 'StartGame' and no extension method 'StartGame' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?)

編輯: 在形式1:

Form2 newForm2 = new Form2(answer, button3, button4, button5, button6, this, fiftyfifty, web, change); 
newForm2.Show(); 

在表格2:

Form originalParent; 
public Form2(int answer, Button button3, Button button4, Button button5, Button button6, Form parentform, int fiftyfifty, int web, int change) 
{ 
    InitializeComponent(); 
    originalParent = parentform; 
} 

,我試圖訪問這個喜歡originalParent."public Method here",它給我的錯誤。

+0

你是否從'Form1'打開'Form2'? – mydogisbox

+0

您需要一個'Form1'類型的變量。你有這樣一個變量嗎?請顯示一些代碼。 –

回答

3

您的Form2構造函數被定義爲在構造函數中獲取通用Form作爲參數。 你需要得到Form1類型的一種形式,所以改變你的Form2構造函數:

private Form1 originalParent; 
    public Form2(
      int answer, Button button3, Button button4, 
      Button button5, Button button6, 
      Form1 parentform, int fiftyfifty, 
      int web, int change) 
    { 
     InitializeComponent(); 
     originalParent = parentform; 
    } 
0

在Form2中將引用強制轉換爲Form1的類型,然後訪問Form1的公共函數。

0

您需要在Form1的實例上調用StartGame,而不是System.Windows.Forms.Form。

如果Form1是Form2的所有者,那麼您需要將所有者轉換爲Form1類型。如果Form1是Form2的Ctor的參數,那麼您需要確保Ctor參數被定義爲類型Form1並從Form2實例保留對Form1的引用。

0

我假設您的Form2構造函數的參數thisForm1實例,並且此代碼因此從Form1調用。

我還假設您有一個Form2 private Form _form1;的私人成員,其值在構造函數中分配。

如果這些假設是正確的,您可以通過將聲明更改爲private Form1 _form1;來解決此問題。

您還需要將構造函數參數的類型從Form更改爲Form1(摘自MusiGenesis)。

2

從您發佈的代碼,我假設你已經寫了Form2一個構造函數,需要一個Form的一個實例。編輯此構造函數,以便代替Form1的實例。或者只是將Form實例施加爲Form1

0

你可以檢查你是否是表單2獲取表單1的實例,其中定義了變量。一旦你擁有了form1實例的實例ID,你就可以調用form 2了,只需要創建一個新的form 1 ref。

I.E.Form1 frm1; public find(Form1 callingform) { InitializeComponent(); frm1 = callingform; }

然後只需調用form 2 form2(this);

0

取決於您爲什麼需要這樣做,您也可以將所需的變量或方法定義爲靜態。在Form1上:

public static int counter; 

Form2上,你可以不經過parentform實例作爲參數傳遞到Form2構造這樣的訪問:

Form1.counter++; 
0

1-關於給你需要選擇那些答案控制並將其修改器設置爲公共,在控件的屬性窗格上,如果您想要Form2與它們進行交互。

2-這部分不是對你的問題的回答,但它可以幫助你理解爲什麼你不應該像你一樣做事情。

我用幾乎相同的代碼創建了一個應用程序,但有人告訴我這不是一個好的做法,甚至不像OOP,所以I posted a question嘗試和學習更多。

看一下,有一些代碼可以幫助您設置不同的東西,甚至可以用您嘗試的方式進行設置。

相關問題