-1

I created a list in my main Form that I wanted to pass to my other forms.

public class MainZoo : Form
{
    public List <Animal> animal;
    public MainZoo(List<Animal> animal)
    {

        InitializeComponent();
        var newAnimal = animal;
    }

That’s my main form, from where I will be open the rest of the forms. I thought I could pass the list using that variable to other forms, when I am opening them. It seems there is an issue in my thinking process, because I can’t "reach" that list from the main form (other forms are inherited from Form, not MainZoo). I was thinking about "get and set", but how? I just saw it, but I don’t know how I should pass that list using that thing.

private void LandAnimalButton_Click(object sender, EventArgs e)
{
    Form Land = new LandAnimalFormcs();
    Land.ShowDialog();
    var newAnimal = animal;
}

This code is still in the main form.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eri
  • 3
  • 2
  • 1
    Why do you have a main Form with a Constructor that requires a `List`, but not the actual Forms that need to receive it? – Jimi May 04 '23 at 18:20
  • Change `Form Land = new LandAnimalFormcs();` to `LandAnimalFormcs landForm = new LandAnimalFormcs();` and then you can do `landForm.animalsList = this.animalList.ToList();` – Dai May 04 '23 at 18:21
  • 1
    You should use the plural form "animal**s**" for collections, not singular. – Dai May 04 '23 at 18:21
  • https://stackoverflow.com/a/73845753/14171304 – dr.null May 05 '23 at 01:01

1 Answers1

-1

Like Dai advised. It would be better if you define the list as a property of the forms you intend to pass the list to. You can use the following code to declare a property that accepts a List and that returns the same from your current form.

public class MyForm : Form {

    // Declare the field to hold the list data in the form
    private List<string> _list;

    // Define the list as a property
    public List <string> MyList {
        get {return _list;}
        set {_list = value;}
    }
}

And then in your other form, where you have a list you are trying to pass to other form, assign like below.

var list = new List<string>();
var form = new MyForm();
form.MyList = list;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Son of Man
  • 1,213
  • 2
  • 7
  • 27