accessing a function in the Program.cs that initializes my Form1 from my Form1

11,098

Solution 1

Putting stuff in Program.cs is not recommended, you should instead create new files.

If you want to put it in Program.cs you just add a method there, you need to make it static since the Program class is static.

To call it from a button, just double click the button in the designer and an event handler is created.

private void button1_Click(object sender, EventArgs e)
{
    Program.YourMethod();
}

The same principle applies if you put the code in another file. Create a namespace and a class in that file.

If you make the class/method non static (that's how you usually do) you need to instantiate your class too.

private void button1_Click(object sender, EventArgs e)
{
    var yourObject = new YourClass();
    yourObject.YourMethod();
}

Solution 2

Assuming the function is public and static, e.g.

public static void Foo()
{
    MessageBox.Show("foo");
}

Simply have such code in the button click event:

Program.Foo();

Solution 3

If you make the method static, you can just call it like this:

class Program
{
    // ...

    public static void SendMessage(object obj)
    {
        // Send your message.
    }
}

Then call the method:

Program.SendMessage(whatToSend);
Share:
11,098
Alex
Author by

Alex

Updated on June 26, 2022

Comments

  • Alex
    Alex almost 2 years

    I've created a server/client application and in my client app i initialized my connection in the Program.cs file in which i also initialize my Form application . How can i, lets say, click on an button on my form and call a function in my Program.cs file ?