Trying to move and item or multiple if selected from one list box to another. The left list box is populated with users searched from AD. I then want to select one or multiple and move them to the right listbox. My issue is i cannot move them. Below code is the function to search and the move function. I am new to WPF so learning and playing to get some understanding. Hoping someone can assist in this.
function SearchDGUserClick
{
param($sender, $e)
$DGMemberSearchListBox.ItemsSource
$query = $DGUserSearchText.Text
$UserSearch = (Get-ADUser -Filter "Name -like '*$query*'") | Select SamAccountName | Sort -Property SamaAccountName
$DGMemberSearchListBox.ItemsSource = $UserSearch
}
function AddUserClick
{
param($sender, $e)
#$UserSearch should be an array or collection of user objects
$DGMemberSearchListBox.ItemsSource = $UserSearch
#Handle the button click or any other event that triggers the move
$selectedItems = @()
foreach ($item in $DGMemberSearchListBox.SelectedItems) {
#If DGMemberAddListBox doesn't have the item yet, add it
if ($DGMemberAddListBox.Items -notcontains $item) {
$DGMemberAddListBox.Items.Add($item)
}
#Remove the item from DGMemberSearchListBox
$selectedItems += $item
}
#Remove the selected items from DGMemberSearchListBox
foreach ($item in $selectedItems) {
$DGMemberSearchListBox.Items.Remove($item)
}
}
Tried playing around with this as well but when i run it, it searches user fine i can select one user, when i click move it clears the left and does not populate the right.
Thanks in advance.
You should not use the ItemsSource
property when you add or remove items from the Items
collection of the ListBox
. It's one way or another but not both.
Try this:
function SearchDGUserClick
{
param($sender, $e)
$query = $DGUserSearchText.Text
$UserSearch = (Get-ADUser -Filter "Name -like '*$query*'") | Select SamAccountName | Sort -Property SamaAccountName
foreach ($item in $UserSearch) {
$DGMemberSearchListBox.Items.Add($item)
}
}
function AddUserClick
{
param($sender, $e)
#Handle the button click or any other event that triggers the move
$selectedItems = @()
foreach ($item in $DGMemberSearchListBox.SelectedItems) {
#If DGMemberAddListBox doesn't have the item yet, add it
if ($DGMemberAddListBox.Items -notcontains $item) {
$DGMemberAddListBox.Items.Add($item)
}
#Remove the item from DGMemberSearchListBox
$selectedItems += $item
}
#Remove the selected items from DGMemberSearchListBox
foreach ($item in $selectedItems) {
$DGMemberSearchListBox.Items.Remove($item)
}
}
It should work assuming your first populate the DGMemberSearchListBox
before you move the items to the DGMemberAddListBox
.