开发者

Selecting items in a ListBox

开发者 https://www.devze.com 2023-01-15 12:10 出处:网络
I have a method that fills a ListBox with objects (custom class) internal void UpdateList() { foreach (Item item in Container.Items)

I have a method that fills a ListBox with objects (custom class)

internal void UpdateList() {
 foreach (Item item in Container.Items)
  List.Items.Add(item);
}

Container also is a custom class that holds a List<Item> where all objects of this container is stored.

Now, the user can select (using a ComboBox) to display a certain Container and I want to select all the Items that this container stores.

I tried it by

private void ContainerList_SelectedIndexChanged(Object sender, EventArgs e) {
 Container container = (Container)ContainerList.SelectedItem;

 foreach (Item item in container.Items)
  List.SelectedIndecies.Add(List.Items.IndexOf(item));
}

But this didn't do the trick: Nothing is selected. I feel the problem is that though the objects in Container.Items and List.开发者_开发问答Items have the same fields, the are not the same for the program.

I hope you understand my problem - How can I get this working?

Edit

To clarify; I want the containers to be editable. So, the user selects a Container from the List and only the Items that are in this container are selected in the ListBox.

The ones not in the Container have still to be in the ListBox, just not selected

So, the user can edit the Items of the container!


1) you can add items to List AFTER a container is selected. so in the list you will have items from only one container.

internal void UpdateList() {
List.Items.Clear(); // delete previos items
 foreach (Item item in Container.Items) // selected container
  List.Items.Add(item);
}

2) you may have a ID for each container so while adding item to the list you may set the item's data with that ID. In SelectedIndexChanged event go via all items and select only ones which have ID of the selected container.


Assuming that List is the ListBox, you can use the AddRange function:

internal void UpdateList()
{
   List.Items.AddRange(Container.Items);
}

Then assuming ContainerList is the ComboBox, you can do this:

private void ContainerList_SelectedIndexChanged(Object sender, EventArgs e) 
{
   Container container = (Container)ContainerList.SelectedItem;

   for(int i = 0; i < List.Items.Count; i++)
   {
      List.Items[i].Selected = container.Items.Contains(List.Items[i]);
   }
}

You will also need to make sure List, the ListBox is setup with multiple selection turned on:

// Set the selection mode to multiple and extended.
List.SelectionMode = SelectionMode.MultiExtended;
0

精彩评论

暂无评论...
验证码 换一张
取 消