Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting items in a listbox using C#

I am using two ListBox controls in my WPF window that are identical (identical = ItemSource of both the ListBox is same and so they look same) and the selection mode on both the ListBoxes is set to Multiple.

Lets call the ListBoxes LB1 and LB2 for the time being, now when I click an item in LB1, I want the same item in LB2 to get selected automatically i.e if I select 3 items in LB1 using either Shift+Click or Ctrl+Click the same items in LB2 get selected.

Have dug the Listbox properties like SelectedItems, SelectedIndex etc but no luck.

like image 688
Anand Shah Avatar asked Mar 20 '09 07:03

Anand Shah


People also ask

How do I select an item in ListBox?

To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected. The following code snippet sets a ListBox to allow multiple selection and selects the second and third items in the list: listBox1.

How do you determine the items that are selected in a ListBox control?

To determine the items that are selected, you can use the Selected property of the list box. The Selected property of a list box is an array of values where each value is either True (if the item is selected) or False (if the item is not selected).

How does ListBox work in C#?

In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events.

Which property is used to select multiple items in a ListBox?

The SelectionMode property enables you to determine how many items in the ListBox a user can select at one time and how the user can make multiple-selections.


1 Answers

Place a SelectionChanged event on your first listbox

LB1.SelectionChanged += LB1_SelectionChanged;

Then implement the SelectionChanged method like so:

void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LB2.SelectedItems.Clear();
    foreach(var selected in LB1.SelectedItems)
    {
        LB2.SelectedItems.Add(selected);
    }
}
like image 193
Arcturus Avatar answered Oct 26 '22 08:10

Arcturus