2010-12-20 45 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) { } 
}