How to access list from another form

前端 未结 2 1400
青春惊慌失措
青春惊慌失措 2021-01-07 08:04

I have two forms, in Form1 a create objects from a class and puts into list (list of objects). then I have another list of strings which is supposed to be a source for

相关标签:
2条回答
  • 2021-01-07 08:11

    Change this:

     Form2 lista = new Form2();
    

    to something like this:

     Form2 lista = new Form2(allPeopleSource);
    

    Remove this from form2:

     Form1 main = new Form1();
    

    And put this code in form2

    List<string> allPeopleSourceInForm2;
    
    Public Form2(List<string> allSourcesAsParameter)
    {
     allPeopleSourceInForm2 = allSourcesAsParameter;
    }
    

    Now your code should work. What we are doing here, is bringing reference of a list to Form2. Form1 contains all the info and we are just passing address of this data to Form2. This reference is brought to Form2 as an constructor parameter. In Form2 constructor we can do what ever we want with data, but be noticed that all the changes into collection at form2 will affect also collection in Form1.

    0 讨论(0)
  • 2021-01-07 08:30

    You can create a method to populate the list on Form2 (I called it SetAllPeople):

    public partial class Form2 : Form
    {
        public void SetAllPeople(List<string> input)
        {
            foreach (string s in input)
            {
                lsbResidents.Items.Add(s);
            }
        }
    
        public Form2()
        {
            InitializeComponent();
        }
    }
    

    and then call Form2 this way:

    Form2 lista = new Form2();
    lista.SetAllPeople(allPeopleSource);
    lista.ShowDialog();
    
    0 讨论(0)
提交回复
热议问题