Home > DeveloperSection > Forums > Update a listbox from another listbox
Simons Hood
Simons Hood

Total Post:70

Points:494
Posted on    January-25-2014 1:36 AM

 C# C# 
Ratings:


 1 Reply(s)
 1080  View(s)
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;

        }

    }



Pravesh Singh

Total Post:411

Points:2881
Posted on    January-25-2014 1:51 AM

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();


Don't want to miss updates? Please click the below button!

Follow MindStick