[Solved] How to pass string value to another form’s load event in C # [duplicate]


There are many ways to do this. The one below is not what I would recommend, but I think it’s the easiest to understand.

Here’s one way to do this:

  1. Create a public static property on your Form1 class to hold the value of this variable
  2. Use the property from step #1 for the MessageBox text
  3. Create a method that will update this property with the text you want
  4. Call the method in #3 when your form loads
  5. Create a common EventHandler method that calls the method in #2
  6. Hook up the TextChanged event of the TextBox objects whose text is used in your string to the common EventHandler created in #4
  7. Reference the property in #2 when your Form2 loads
    • My example assumes you have a Label named label1 on the Form that you want to update with the text

Here’s how:

public partial class Form1 : Form
{
    // 1. This class-level variable will hold our string
    public static string PrintMessage { get; private set; }

    // 2. Reference your strPrint variable for the MessageBox as you were before
    private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show(PrintMessage);
    }

    // 3. This method will update our string with values from TextBoxes
    private void UpdateText()
    {
        PrintMessage = "Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text +
            "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text +
            "\n Net = " + txtNet.Text;
    }

    // 4. Call our update method when the Form loads
    private void Form1_Load(object sender, EventArgs e)
    {
        UpdateText();
    }

    // 5. This EventHandler just calls our update method
    private void CommonTextChangedEvent(object sender, EventArgs e)
    {
        UpdateText();
    }

    // I have a `button1` on my Form1, and clicking this button shows Form2
    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2();
        form2.Show();
    }

Now, hook up the event handler. The easiest way is:

  1. One at a time, select one of the textboxes whose Text is used in our string
  2. In the Properties window, click the Events button (looks like a lightning bolt)
  3. Choose the TextChanged event, and assign our new method to it

enter image description here

Now, in your Form2 class, you should be able to reference the Form1 property you created in #1:

public partial class Form2 : Form
{
    private void Form2_Load(object sender, EventArgs e)
    {
        label1.Text = Form1.PrintMessage;
    }

To test it, just run the project, change the text in the text boxes, and click the button to load Form2

1

solved How to pass string value to another form’s load event in C # [duplicate]