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;
                        }
                    }
                }

Edited 6 Years Ago by empyrean: n/a

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

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

This question has already been answered. Start a new discussion instead.