2015-08-24 30 views
-3

我在Form1中有一個int數組,我需要在Form2中使用。但是當我試圖使用Form2中的數組值時,它給了我零。無法在Form2中使用Form1中的int數組

private void button1_Click(object sender, EventArgs e) 
{ 
    frm1 = new Form1(); 

    for (int i = 0; i < 26; i++) 
    { 
     label1.Text += frm1.theCode[i]; 
    } 
} 

http://i59.tinypic.com/b4cf2b.png http://i59.tinypic.com/b4cf2b.png

但是當我嘗試在Form1中同樣的事情,它的偉大工程!

private void button5_Click(object sender, EventArgs e) 
{ 
    frm2 = new Form2(); 

    for (int i = 0; i < 26; i++) frm2.label1.Text += theCode[i]+ " "; 

    frm2.Show(); 
} 

http://i59.tinypic.com/jujthi.png http://i59.tinypic.com/jujthi.png

但我仍然需要使用數組中Form2,不Form1

+2

使用數組這幾乎肯定是因爲你的構造不填'theCode'與價值觀。 '新的Form1()'不會*給你一個指向屏幕上當前窗體的指針。它創建了一個**新的**。 – Rob

+0

第一個代碼屬於哪種形式?您將值分配給當前表單的'label1',而不是'frm1'。在第二種情況下,您實際上正在修改'frm2'的標籤,所以這就是它的原因。 – Andrew

+0

第一個代碼屬於Form2。我應該如何編輯代碼才能使其正常工作? –

回答

0

Form1您必須聲明,以便從另一種形式訪問int數組作爲靜態字段和公衆。

因此,這是你如何在Form1

public static int[] theCode; // should be public and static 

聲明theCode這是你如何在Form2

private void button1_Click(object sender, EventArgs e) 
{ 
    // no need to create new instance of Form1. 
    for (int i = 0; i < 26; i++) 
    { 
     label1.Text += Form1.theCode[i]; // use the static field 
    } 
} 
+1

儘管有效,但完全需要這樣做意味着您已經完成了可怕的錯誤(這在生產代碼/系統中很容易出錯)。更好的辦法是簡單地將你的邏輯與你的觀點分開並傳遞出去。 – BradleyDotNET

+0

非常感謝你!現在它的作品! –