• 0

C# Newb Question


Question

I'm a newb to C# and I was wondering how you communicate with WinForms? It seems that I can call the functions of Form2 but not Form1 (the main form). I'm using a code similar to below to call a method in Form1:

Form1 form1 = new Form1();

form1.change(50);

And in Form1, I defined this method:

public void change(int val2) {

this.Opacity = (val2 * 0.01);

}

It doesn't seem to work. Any suggestions?

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

You can do a couple of things. You can specify an overloaded constructor for Form2 that takes another form as a parameter passing in Form1, or you can set the Parent property of Form2 to Form1.

Link to comment
Share on other sites

  • 0

Sorry, as I've said I'm a newbie at this. Could you please post an example code? I need to send a variable local to Form2 over to Form1.

Edited by Blackout
Link to comment
Share on other sites

  • 0

I guess I should ask how you're creating Form2. If you're creating Form2 from Form1, then it's simple.

Form2 f2 = new Form2();
f2.Parent = this; // this is referencing the instance of Form1

// calling Form1 from form2
Form1 f1 = (Form1)this.Parent;
f1.change(50); //... or whatever

If you go the overloaded constructor route...

private Form1 mForm1;
public Form2(Form1 form1)
{
    mForm1 = form1;
}

// calling form1
mForm1.change(50);

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.