TimeToCode TimeToCode - 2 months ago 7
C# Question

Fill a List<String> of a Winform from other Winform while both forms are active

I'm trying to fill a

List<String>
from another form while both forms are open.

In the form
WorkOrder
i have a list:
List<String> materialsList
, then in my other form
AddMaterials
i have other
List<String> list
, this is the list that i want to pass to the
WorkOrder
form, but both forms are open and i don't know it is possible to do that.

Here are my forms:

enter image description here

If i click the Add Materials button in the
WorkOrder
form then the form
AddMaterials
opens. Now with the form
AddMaterials
open, i fill one by one the elements of the list with the button Add new Material, then when i click finish i want to pass the
List<String> list
to the
WorkOrder
list:
List<String> materialsList
.

This is the code that i'm trying to solve this:

In the
WorkOrder
form:

List<String> materialsList = new List<string>();

public void setList(List<String> l)
{
this.materialsList = l;
}


In the
AddMaterials
form:

public partial class AddMaterials : Form
{

List<String> list = new List<string>();

public AddMaterials()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//Adding Materials
list.Add(material.Text);
}

private void button2_Click(object sender, EventArgs e)
{
//Passing the list with Method setList()
WorkOrder o = new WorkOrder();
o.setList(list);
}
}


Any question post on comments.

Answer

You could pass a reference to either the WorkOrder Form or the WorkOrder.materialsList in the constructor of your AddMaterials Form. So your AddMaterials code could be

public partial class AddMaterials : Form
{
    WorkOrder wo;

    public AddMaterials(WorkOrder wo)
    {
        InitializeComponent();
        this.wo = wo;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Adding Materials
        this.wo.materialsList.Add(material.Text);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }   
}

In WorkOrder you'd have this function which opens a new AddMaterials Form. You could place in logic here before you create a new AddMaterials Form to clear the list or do something else if you have multiple materials list for a WorkOrder.

private void button1_Click(object sender, EventArgs e)
{
    // Add logic here to deal with multiple AddMaterial Forms 
    // on one work order
    new AddMaterials(this).Show();
}