User3283827 User3283827 - 2 months ago 24
C# Question

How to Update a Listbox from another Listbox

I have two listboxes in two separate forms Once one is filled out and a button click event is used I want the data from that listbox in this instance a bunch of scores to be transmitted to the other form. My issue thus far is converting my listbox in my second form to an arraylist.

Code Below:

Form1

Form3 newForm1 = new Form3(this);
newForm1.ShowDialog();

foreach (string s in newForm1.updateStudentInfo)
{
listForm1.Items.Add(s);
}


Form2:

public List<string> updateStudentInfo { get; set; }

string student = txtName.Text;
string[] stuffFromList = listboxscores // Unsure how to transfer into an arraylist


for (int i = 0; i < stuffFromList.Length; i++)
{
student = student + "|" + form3.listForm1.Items.Add(stuffFromList[i]);
}

updateStudentInfo.Add(student);
form3.listForm1.Items.RemoveAt(form3.listForm1.SelectedIndex);
this.Close();
}

Answer Source

So what you really need help with is getting list box items into an array/list? This should do it: This of course is assuming your rest of the code works.

List<string> items = new List<string>();
if (lbScores.Items != null && lbScores.Items.Count > 0)
{
    foreach (var item in lbScores.Items)
    {
        items.Add(item.ToString());
    }
}

Here I rewrote the code so you could better understand.

private void btnOK_Click(object sender, EventArgs e)
{
    string student = txtName.Text;
    if (lbScores.Items != null && lbScores.Items.Count > 0)
    {
        foreach (var item in lbScores.Items)
        {
            student = student + "|" + item.ToString();
        }
    }

    updateStudentInfo.Add(student);
    form3.listForm1.Items.RemoveAt(form3.listForm1.SelectedIndex);
    this.Close();
}