Alex Alex - 1 month ago 6
C# Question

Call another form functions from the first form

I hope the title is clear enough. Let me explain : I am doing a c# Winform App. When I start the app I have my Form 1 which starts, and I have other forms I can open from it by clicking buttons.

The problem is, I have functions in those Forms (Form 2, Form 3, Form 4..) I want to start from the Form 1 .

Currently here's my code

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

// First Event, when I click in the toolstrip menu, I open the Form2 ("Ligne3")
private void ligne3ToolStripMenuItem_Click(object sender, EventArgs e)
{
var Ligne3 = new Ligne3();
Ligne3.Show();
}


Then, I have components in the Form2 (textboxs, buttons, functions etc)

public partial class Ligne3 : Form
{

public Ligne3()
{
InitializeComponent();
}

private void Ligne3_Load(object sender, EventArgs e)
{
//Some code
}
}

//Function I want to call from the Form1
public void send_email()
{
//Some code
}


How can I start my " send_email() " function from the Form1 (for example during Load Event) ?

Answer

Assign the values of Form2 or any other objects/variables to Linge3 object before calling show. Values which are needed in send_email() to be assigned before calling send_email(). Something like below.

private void ligne3ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var ligne3 = new Ligne3();
        //define variables/properties in Ligne3 for all values to be passed
        //then assign them with corresponding values
        ligne3.Value1 = objForm2.Value1; 
        ligne3.Value2 = objForm2.Value2; 
        ligne3.Value3 = objForm2.textBox1.Text;
        ligne3.Value3 = objForm2.checkBox1.Value;
        //and so on
        ligne3.send_email();
        ligne3.Show();
    }