Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access list from another form
    text
    copied!<p>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 <code>Form2</code> - the list of strings contains elements which are object's attributes turned into strings. <code>Form2</code>, after opening, should read the data from the list of strings and put them into listbox. The problem is it does not see the data. I can access data in <code>Form1</code>, so I'm sure the list is populated, but Form2 cannot access the data - how to solve this?</p> <p>I have tried different ideas taken from the forum and other sources but none of them worked for me. what worked was populating the list which is supposed to be a data source in Form1 'initialize component' but it is not a perfect solution since objects are created after clicking a button. now I put the list at the top of the Form1 class but it is still populated by clicking a button - and it does not work, the listbox is still empty.</p> <p>Here is the code of <code>Form1</code>:</p> <pre><code>public partial class Form1 : Form { public House MyHouse = new House(); public List&lt;string&gt; allPeopleSource = new List&lt;string&gt;(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Person p1 = new Person("Simon", 33); Person p2 = new Person("Peter", 23); MyHouse.IsInhabitedBy(p1); MyHouse.IsInhabitedBy(p2); allPeopleSource.Add(p1.Name + " | " + p1.Age.ToString()); allPeopleSource.Add(p2.Name + " | " + p2.Age.ToString()); Form2 lista = new Form2(); lista.ShowDialog(); } } </code></pre> <p>Here is the code of <code>Form2</code>:</p> <pre><code>public partial class Form2 : Form { Form1 main = new Form1(); List&lt;string&gt; allPeople = new List&lt;string&gt;(); public Form2() { InitializeComponent(); foreach (string s in main.allPeopleSource) { allPeople.Add(s); } foreach (string s in allPeople) { lsbResidents.Items.Add(s); } } } </code></pre> <p>I appreciate any help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload