How can I access my method from another class

I’m very new to c#, I started a few days ago, so please excuse me if it is basic.
I have two forms, the first one is like a login page, where someone enters their name. On my "Info.cs" class, it reads this name via a setter, into a variable, and my Getter called "GetCardName" returns this Name. I now made a new form where I want to access this name via the GetCardName getter, just dont know how too. Heres the code :

Here is some of the "info.cs" class code:

private string CardName { get; set; } = "";
   
public string GetCardName()
{
    return this.CardName;
}

public void SetName(string name = "")
{
    this.CardName = name;
}

And here is the code from the other form that is just trying to call GetCardName():

private void Form2_Load(object sender, EventArgs e)
{
    lblWelcome.Text = Info.GetCardName();
}

>Solution :

When creating Form2 you need also pass it reference to the other form to get its properties.

So when creating and showing Form1 you should also create Form2 to pass that reference. Example (not tested) code:

var form1 = new Form1();
var form2 = new Form2(form1);
form1.Show();

and Form2 should be like:

public class Form2
{
    private Form1 _form1;

    public Form2(Form1 form1)
    {
        _form1 = form1;
        // ... other initialization code
    }
    
    // ... other class declarations
}

General solution is: you need to persist reference to the Form1 being shown to the user and then pass that reference to Form2 whenever you create it.

Leave a Reply