Click here to Skip to main content
15,887,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
This code below works well thanks to you.
Please for just one more question.
I would like to add items from Form2 to listBox1 - Form1.
Form2 has textBox1 and textBox2 and button1.
On Form1 I have listBox1
I want to use this code below in this manner described above. Thanks.


C#
foreach (var item in textBox2.Lines.Select(l => textBox1.Text + " " + l).ToArray())
            {
                if (!listBox.Items.Contains(item))
                    listBox1.Items.Add(item);
            }


What I have tried:

something like:
Form1:

private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Owner = this;
f2.ShowDialog();
}

public void AddListItem(object text)
{
listBox1.Items.Add(text);
}

Form2:
private void cmdOK_Click_1(object sender, EventArgs e)
{
Form1 f1 = (Form1)Owner;
foreach (var item in textBox2.Lines.Select(l => textBox1.Text + " " + l).ToArray())
f1.AddListItem(item)
Close();
}
Posted
Updated 4-Oct-16 18:47pm
Comments
[no name] 4-Oct-16 12:06pm    
"I want to use this code below in this manner described above", okay so go ahead and do that. Do you have an actual question that you wanted to ask? Pretty bad idea if you ask me. Your forms should not have any dependencies on each other, especially for UI controls.

Stop doing that. Don't pass form references between forms - it ties them together and make it a lot harder to maintain everything later.
Instead, set up a property in Form2 which returns the information Form1 wants to display, and let it decide what to do with it:
C#
Form2 f2 = new Form2(); 
f2.ShowDialog();
string[] data = f2.Results;
listbox1.AddRange(data);

The Results property returns the distinct values as assembled in your previous questions.

That way, Form2 doesn't have to know that Form1 even exists, and nothing needs to be exposed making maintenance difficult later.
 
Share this answer
 
try this to update the data in parent form

C#
foreach (Form f in Application.OpenForms)
          {
              if (f.Name == "Form1")
              {
                  (f as Form1).AddListItem(item);
              }
          }


or

C#
Form form1 = Application.OpenForms.OfType<Form>().SingleOrDefault(k => k.Name == "Form1");
         if (form1 != null)
             form1.AddListItem(item);
 
Share this answer
 
v2
Simple: do the test in the AddListItem method of Form1 instead of cmdOK event handler of Form2.
C#
using System.Linq;

public void AddListItem(object text)
{
   if (!listBox1.Items.Any(item => item.Text == text))
   {
      listBox1.Items.Add(text);
   }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900