tags:

views:

240

answers:

3

Instead of adding each item one by one to the ListBox destinationList from the string array m_List like this:

foreach (object name in m_List)
{
    destinationList.Items.Add((string)name);
}

Is there any better way I can do it?

I don't want to bind the data to the destinationList since I want to delete some entries from the ListBox later on.

A: 

use OberservableCollection

Kishore Kumar
how can i use it? you mean instead of string array?
Archie
@Archie: You'll have to copy your array contents into ObservableCollection and then bind the OC to the ListBox, if you want to preserve the original contents.
Veer
+1  A: 

HTH:

    string[] list = new string[] { "1", "2", "3" };

    ObservableCollection<string> oList;
    oList = new System.Collections.ObjectModel.ObservableCollection<string>(list);
    listBox1.DataContext = oList;

    Binding binding = new Binding();
    listBox1.SetBinding(ListBox.ItemsSourceProperty, binding);

    (listBox1.ItemsSource as ObservableCollection<string>).RemoveAt(0);

Just use (ItemSource as ObservableCollection)... to work with items, and not Items.Add etc.

Andrew
It gives error since if the parent checkbox is checked all the child checkboxes' checked event is called and it throws same error.Instead of adding a single item as Items.Add what can be done?
Archie
Sorry, but i don't understand you, parent checkbox? Can you post some code, or describe your problem with more details?
Andrew
Plz read the comments in the question for clarification.
Archie
If you bind listview to source, you must work with source, and not with the listviewitems. As for you problem, i have to see code, which throw exception. This kind of exception usually happend if you work not with the source but with items instead. And as for the checkbox logic it's up to you (if it's in you code), you can change check behavior (i'm talking about treeview) if you don't like it.
Andrew
A: 

Okay.. if binding is not an option - and I would probably go that way if it was... then the only more efficient way to populate the listbox would be to do it in parallel.

(For this to work I am assuming you have the .Net 4 runtime, or the PLinq libraries installed)

The following code would show massive improvements on a multicore machine provided the collection of data was large enough to warrant the overhead of the initial setup. So this would only be viable for larger arrays.

Parallel.ForEach(list, r => destinationList.Items.Add(r));

Else I don't see anything wrong with your foreach loop.

Mark Pearl