0

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

2
  • On what class is this method declared? Do you have a reference to the object on which this method should be invoked at the point the button is created / clicked? What arguments should be passed to the method?
    – Ani
    Dec 20, 2010 at 9:51

5 Answers 5

6

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).

2
  • thanks,what 10,20 work here?cant i define variable instead of 10,20
    – Arash
    Dec 20, 2010 at 10:03
  • @arash - Of course you can. This was an example, to show how this will work. @Rajesh Kumar G used (5,6) as an example.
    – Oded
    Dec 20, 2010 at 10:05
3
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);
}
3

call the function in the button click event

for ex :

    private void button1_Click(object sender, EventArgs e)
    {

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

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);
1

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) { } 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.