Reputation: 3051
i have a simple question:i have for example
public int X(int a,int b)
{
}
now how can i call this when click button?i mean when i click the button,X() call and work,thanks for your helps
Upvotes: 0
Views: 27791
Reputation: 498904
You need to make the method call in the event handler for the button click.
In Visual Studio, when in the designer if you double click on the button, an empty click event handler should be created and hooked up for you.
private void Button1_Click(object sender, EventArgs e)
{
// Make call here
X(10, 20);
}
I suggest you read this whole topic in MSDN (Creating Event Handlers in Windows Forms).
Upvotes: 6
Reputation: 13278
Add your X() method as a delegate to the button click event:
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) { }
}
Upvotes: 1
Reputation: 1534
call the function in the button click event
for ex :
private void button1_Click(object sender, EventArgs e)
{
int value = X(5,6);
}
Upvotes: 3
Reputation: 166336
private void button1_Click(object sender, EventArgs e)
{
int retVal = X(1,2);
}
or if this is part of a class
public class Foo
{
public int X(int a, int b)
{
return a + b;
}
}
then something like
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);
}
or if it is a static member
public class Foo
{
public static int X(int a, int b)
{
return a + b;
}
}
then something like
private void button1_Click(object sender, EventArgs e)
{
int retVal = Foo.X(1, 2);
}
Upvotes: 3
Reputation: 1038710
It looks like this is an instance method. So the first thing is to obtain an instance of the class containing this method. Once you have an instance you can invoke the method on it:
var foo = new Foo();
int result = foo.X(2, 3);
If the method is declared static you no longer need an instance:
public static int X(int a,int b)
{
}
and you could invoke it like this:
int result = Foo.X(2, 3);
Upvotes: 2