2010-12-20 38 views
0

我有一個簡單的問題的方法:當點擊按鈕,我的意思是,當我按一下按鈕,X()調用我有例如我怎麼能叫使用按鈕

public int X(int a,int b) 
{ 
} 

現在我怎麼能叫這和工作,感謝你的幫助

+0

檢查http://www.microbion.co.uk/developers/C%20event %20handlers.pdf – 2010-12-20 09:49:38

+0

該方法聲明瞭什麼類?在創建/單擊按鈕的位置,您是否應該引用此方法應該在其上調用的* object *?應該傳遞什麼參數給該方法? – Ani 2010-12-20 09:51:25

回答

3
private void button1_Click(object sender, EventArgs e) 
{ 
    int retVal = X(1,2); 
} 

,或者如果這是一個類的一部分

public class Foo 
{ 
    public int X(int a, int b) 
    { 
     return a + b; 
    } 
} 

事遂所願

private void button1_Click(object sender, EventArgs e) 
{ 
    int retVal = new Foo().X(1, 2); 
    //or 
    Foo foo = new Foo(); 
    int retVal2 = foo.X(1, 2); 
} 

,或者如果它是一個靜態成員

public class Foo 
{ 
    public static int X(int a, int b) 
    { 
     return a + b; 
    } 
} 

事遂所願

private void button1_Click(object sender, EventArgs e) 
{ 
    int retVal = Foo.X(1, 2); 
} 
6

您需要在該按鈕單擊事件處理程序的方法調用。

在Visual Studio中,在設計的時候,如果你在按鈕上雙擊,應創建一個空的單擊事件處理程序,並迷上了你。

private void Button1_Click(object sender, EventArgs e) 
{ 
    // Make call here 
    X(10, 20); 
} 

我建議你閱讀在MSDN this whole topic(在Windows窗體創建事件處理程序)。

+0

感謝,這裏什麼工作10,20我不能定義變量,而不是10,20 – Arash 2010-12-20 10:03:33

+0

@arash - ?當然可以。這是一個例子,以顯示這將如何工作。 @Rajesh Kumar G以'(5,6)'爲例。 – Oded 2010-12-20 10:05:32

2

它看起來這是一個實例方法。所以首先要獲得包含此方法的類的實例。一旦你有一個實例可以在其上調用方法:

var foo = new Foo(); 
int result = foo.X(2, 3); 

如果方法聲明爲static您不再需要一個實例:

public static int X(int a,int b) 
{ 
} 

,你可以調用它是這樣的:

int result = Foo.X(2, 3); 
3

呼叫按鈕單擊事件功能

爲前:

private void button1_Click(object sender, EventArgs e) 
    { 

     int value = X(5,6); 
    } 
1

添加您的X()方法作爲代表到按鈕單擊事件:

public partial class Form1 : Form 
{ 
    // This method connects the event handler. 
    public Form1() 
    { 
    InitializeComponent(); 
    button1.Click += new EventHandler(X); 
    } 

    // This is the event handling method. 
    public int X(int a,int b) { } 
}