I have two list boxes in two different forms.. I load the data in to second list box using first list box...both have exactly same values.. but in first list box user selects multiple selections and i wanted to show them in second listbox as selected.. i have the following code but its only highlighting last item from selected items..please suggest me the modifications..

this.lstView2.ItemsSource = lstView1.ItemsSource;
//the above statement brings the values from lstView1 into lstView2

               foreach (DataRowView currentItem in lstView2.Items)
                {
                    foreach (DataRowView item in lstView1.SelectedItems)
                    {
                        if (currentItem == item)
                        {
                            lstView2.SelectedItem = currentItem;
                        }
                    }
                }

Can anyone suggest modifications for me please :( ,....

Actually i am using list views not the list boxes.. please some one suggest me the modifications in my code..

You need to add items to the SelectedItems collection rather than chanign the single SelectedItem value:

foreach (object item in listBox1.SelectedItems)
    {
        listBox2.SelectedItems.Add(item);
    }

works like a champ...thank you soo much..

hmm..if its a listview there are a couple of extra steps.
Ensure you have the same items in each list and in the same order and use the Index of each selected item:

foreach (ListViewItem item in listView1.SelectedItems)
    {
        listView2.Items[item.Index].Selected = true;
    }

I'd suggest you set the HideSelection property to false to ensure the selected items are still highlighted when the listview has lost focus

Oh, didnt think the first method would work with a listview. Oh well, ignore my last post..Happy to help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.