3

So I have 2 forms and need to pass a property from one form to the other.

On Form 1 I have a method

 private void rb_CheckedChanged(object sender, EventArgs e)
    {
        var frm2= new Form2();
        WorkComplete += frmSetNewTime.btnOk_Click;
        frmSetNewTime.Show();
    }

    private void WorkComplete(object sender, EventArgs e)
    {
     //   Property = Property from form 2
    }

On Form2 I have a method called btnOK_Click

public void btnOk_Click(object sender, EventArgs e)
    {
        Property = 5
     }

My goal is to pass the property from form2 back to form 1.

I cant subscribe WorkComplete because it is a method group is the error I get. Does anyone know the proper way, or maybe proper syntax, to do this?

DidIReallyWriteThat
  • 1,033
  • 1
  • 10
  • 39

2 Answers2

2

1) Create a new project with 2 forms.

2) On Form2, create a button.

3) In the button's properties, change Modifiers to Internal. Normally, this is Private, which means only Form2 can access button1 and its properties. Changing it to Internal allows any class within the assembly to access button1. If you were to change it to Public, you can also allow libraries that you reference in your project to access button1 as well.

4) On Form1, add the following code within the class:

    Form2 frm;

    private void Form1_Load(object sender, EventArgs e)
    {
        // Create and show the form.
        frm = new Form2()
        frm.Show();

        // Assign the event handler for the button to a handler within this class.
        frm.button1.Click += this.Form2_button1_Click;
    }

    // This is the event handler that will run when you click the button on Form2.
    private void Form2_button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked the button on Form 2!");
        var frmProperty = frm.Property;
    }
roncli
  • 196
  • 2
  • 8
1

Try this:

public event OnWorkCompleted;

public void WorkComplete()
{
   if(OnWorkCompleted != null)
       OnWorkCompleted(Property, null);
}

On the subscriber form :

Form1.OnWorkCompleted += Form1WorkCompleted;

public void Form1WorkCompleted(object sender, EventArgs e)
{
    var property = (int)sender;
    MessageBox.Show('hey form 1 property is ' + property.);
}

Hope this helps.

syntax error
  • 149
  • 1
  • 5