2012-05-05 14 views
0

如何使用我在Form()函數中定義的變量在按鈕單擊事件中使用?C#Windows應用程序傳遞變量到按鈕單擊功能

public Form2(string a, string b) 
    { 
     int something=4; 
     int something=5; 
    } 

public void hButton_Click(object sender, EventArgs e) 
    { 

    } 

我想在該gButton_Click事件中使用變量some​​thing和something2。我怎樣才能做到這一點?

回答

1
class Form2 { 
    int something, something; 
    public Form2(string a, string b) { 
     something=4; 
     something=5; 
    } 
    public void hButton_Click(object sender, EventArgs e) { 
     // example: MessageBox.Show(something.ToString()); 
    } 
} 
0

你不能用你寫的代碼,因爲「東西」變量只存在於form2()函數的範圍內。如果你將它們聲明爲類變量,那麼你就可以在按鈕點擊功能中訪問它們。所以像這樣:

class form2 
{ 
    int something; 

    public Form2(string a, string b) 
    { 
     something=4; 
     something=5; 
    } 

    public void hButton_Click(object sender, EventArgs e) 
    { 
     //now you can access something in here 
    } 
} 
相關問題