I apologize in advance because I imagine this is a duplicate question but I've been searching for an answer for about an hour and I've yet to find one that resolves my problem.
Basically, I'm trying to call a non-static method from another file and class. My code is as follows:
Form1.cs
:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public void SwapPositions()
{
text1.Location = new Point(73, 101);
label1.Location = new Point(12, 111);
}
}
}
I'm trying to call the function like this but it does not work:
Settings.cs
:
namespace WindowsFormsApp1
{
public partial class Settings : Form
{
// some code //
Form1 t = new Form1();
t.SwapPositions();
}
}
Could anyone explain to me why this doesn't work and how to change my code so as to make it work?
When you do Form1 t = new Form1()
it creates a new form. To invoke the SwapPositions
Method on your form do this:
namespace WindowsFormsApp1
{
public partial class Settings : Form
{
Form1 frm = null;
public Settings(Form1 frm)
{
this.frm = frm;
}
public void MethodWhereSwapPositionsGetsInvoked()
{
frm.SwapPositions();
}
}
}
And create a instance of Settings
with this:
Settings settings = new Settings(this);