Update a listbox from another listbox

Total Post:70

Points:494
C# 
C#
 1668  View(s)
Ratings:
Rate this:

I have two Winforms (admForm and projForm) and each have a listbox. Inside the admForm you can add a user in the list box that belongs to this form.

Everything works fine so far, but I would like to update the listbox in "projForm" with objects that are in the list box in "admForm".

Any idea?

In admForm:

public string ListBox
{
    get { return lstUserOrProject.Items.ToString(); }
}

In projForm:

private void UpdateList()
{
    AdminForm admForm = new AdminForm();
    lstAvailableUser.Items.Add(admForm.ListBox.ToString());
}

Code to open the projForm:

    private void btnAdd_Click(object sender, EventArgs e)
    {
        int index = lstUserOrProject.SelectedIndex;
        switch (cmbUserOrProject.SelectedIndex)
        {
            case (int)UserOrProject.Projects:
                ProjectForm proj = new ProjectForm("Add Project");
                if (proj.ShowDialog() == DialogResult.OK)
                {
                    projMngr.AddProject(proj.ProjectData);
                    UpdateProject();
                }
                break;
            case (int)UserOrProject.Users:
                UserForm user = new UserForm("Add User");
                if (user.ShowDialog() == DialogResult.OK)
                {
                    userMngr.AddUser(user.UserData);
                    UpdateUser();
                }
                break;
        }
    }
  1. Post:412

    Points:2888
    Re: Update a listbox from another listbox

    Hi samuel.

    AdminForm admForm = new AdminForm();

    You are creating completely new instance.

    If you are open your projForm after your AdminForm, when you are showing your form use this code:

    ProjForm projForm = new ProjForm();  // change ProjForm if your form class name is different

    projForm.Show(this);

    Then in your projForm you can access your listBox like this:

    private void UpdateList()
    {
      var items = Owner.lstUserOrProject.Items; // Owner represents your admin form
      lstAvailableUser.Items.Clear();
       foreach(var item in items)
       {
          lstAvailableUser.Items.Add(item);
       }
     }

    Update:

    Move this definition to the top of your page in AdminForm, i mean:

    class AdminForm : Form
    {
       // move your definition here
       ProjForm projForm = new ProjForm();  // change ProjForm if your form class name is different
    }

    Then when you want to show your form call:

    projForm.Show(this);

    When you want to update your list in the projform call your update method:

    projForm.UpdateList();

      Modified On Apr-04-2018 01:49:19 AM

Answer