Visual C# - Access instance of object created in one class in another
Asked Answered
D

4

14

I apologize in advance with what will probably be a fairly easy/quick answer based on scope, but I've looked everywhere and am surprised to not come up with an answer.

I have created a class called Soldier with roughly 100 class variables. I need a user to enter information and gradually build a Solider object over the course of several different class Forms (because there is too much data to collect on just one).

I create an (empty) instance of a Soldier (tempSoldier) in Form1.cs and start to set the object's class variables that I collect from the user.

private void button1_Click(object sender, EventArgs e)
{
    Soldier tempSoldier = new Soldier();
    tempSoldier.surname = textbox1.text;
}

My question: how do I gain access to the object instance (tempSoldier) from Form1.cs in the other classes (Form2.cs, Form3.cs ...)?

I should mention that all of the Forms (Form1.cs, Form2.cs ...) share the same namespace.

Thanks in advance

Edit: All solutions below work so it just depends upon which one you like the best. Thank you for your feedback. One little note, make sure you make ALL of the class modifiers Public including your custom class (in my case Soldier.cs).

Donley answered 9/9, 2012 at 1:46 Comment(1)
Your local declaration will have a very brief lifespan. If you declared it in the form rather than a method in the form, you could refer to it elsewhere as Form1.tempSoldier.Sprue
B
13

You'll need to declare the Soldier instance in in a higher scope.

One way of doing this would be to declare it inside Form1, then pass it to Form2, and so on.

public class Form1
{
    private Soldier tempSoldier = new Soldier();

    private void button1_Click(object sender, EventArgs e)
    {
        tempSoldier = new Soldier();
        tempSoldier.surname = textbox1.text;
    }

    private void GotoNextStep()
    {
        // pass the existing instance to the next form
        Form2 form2 = new Form2(tempSoldier);

        // display form 2 ...
    }
}

Another possibility is to use a singleton variable in a class that all the forms have access to.

public class MyAppManager
{
    private static readonly Soldier _soldier = new Solider();

    public static Soldier SoldierInstance
    {
        get { return _soldier; }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MyAppManager.SoldierInstnace.surname = textbox1.text;
}

The former approach is ok if there's a distinct sequence to the forms; the latter is better if difference forms could be used at different times or revisited.

Bolzano answered 9/9, 2012 at 1:51 Comment(5)
I tried the first solution but I got a strange error on the Form2 constructor (inconsistent accessibility...) when I tried to add a parameter (not sure why because it seemed very logical). The second solution was the simplest/cleanest and it worked fine.Donley
If memory serves, you just need to make sure that the class for the form and the class for Soldier have the same accessibility.Everhart
Both are listed as Public and I'm still getting the same error?Donley
Dumb mistake...when I declared the Soldier class{...} I forgot to add the Public modifier (forgetting that by default it is set to Private).Donley
This is a great example, one of the best I've found. But if you are trying to populate members in the Solder instance it cannot be readonly. You will need to remove the readonly modifier to be able to make changes to the instance, not sure why McGarnagle chose to put it in there.Farnsworth
R
5

You can also make Soldier a static variable :

public static Soldier soldier {get;set;}
private void button1_Click(object sender, EventArgs e)
{
    soldier = new Soldier();
    soldier.surname = textbox1.text;
}

Code in other forms:

Form1.soldier.name ="";
Reconnoitre answered 9/9, 2012 at 8:12 Comment(1)
This seems like the most elegant solution.Donley
T
3

You should create a public property on your form that exposes the soldier. You can then access this property from the other forms.

// ...

public Soldier Soldier { get; private set; }

private void button1_Click(object sender, EventArgs e)
{
  Soldier tempSoldier = new Soldier();
  tempSoldier.surname = textbox1.Text;

  this.Soldier = tempSoldier;
}

// ...

Your Form2 class could look something like this:

public partial class Form2
{
  private Form1 form1;

  public Form2(Form1 form1)
  {
    this.form1 = form1;

    this.InitializeComponent();
  }

  public void DoStuffWithForm1()
  {
    // ...

    string surname = this.form1.Soldier.surname;

    // ...
  }
}
Tyrannous answered 9/9, 2012 at 1:54 Comment(2)
I get the same error message as the previous answer: "Inconsistent accessibility: property type is less accessible than property" for the first line: public Soldier Soldier { get; private set; } I understand it has to do with the modifiers, but every one is listed as Public and yet the error remainsDonley
Dumb mistake...when I declared the Soldier class{...} I forgot to add the Public modifier (forgetting that by default it is set to Private).Donley
G
0

In your other class, create a method with objects as parameters.

public class TryMe (TextBox newTextbox) {
newTextbox.Text = "Hello this is a text."
//You can also get the value of textbox of another form
var textString = newTextbox.Text;
}

And then in your main form, call that method with your objects as parameters. In this case, add textbox1 to your method's parameter.

Your code in form:

TryMe(textbox1);
Gao answered 18/6, 2020 at 1:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.