Clint Clint - 2 months ago 10
C# Question

C# WPF Random ListBox - Remove object from one list box and add to another using a random

I am using a basic WPF application. In it I have a list of Persons with a few properties. When I run the application it populates a listbox with the Persons. I have a button to random an Persons based off of a selection(1-5). When this happens, I need to remove that Person/s and move him/her to another list box I have.

I get an error while in the first foreach loop. Not sure how to loop through the personListBox. Also need to move the person from personListBox1 to personListBox2.

I need the person removed from the 1st list so that when it loops again, it will not be there to be selected again. I plan on doing something with only the second list of persons. Thanks in advance guys.

Below is the random button I am trying this with.

private void randomButton_Click(object sender, RoutedEventArgs e)
{
if (this.numberComboBox.SelectedIndex != -1)
{
List<Person> personList = new List<Person>();
int number = Convert.ToInt16(this.numberComboBox.SelectedItem);

// Add each person from the one list box to the other.
foreach (Person P in this.personListBox.Items)
{
personList.Add(P);
}

// Loop the the selected number of times to remove and add from list to list.
for (int i = 0; i < number; i++)
{
int randomValue = random.Next(personListBox.Items.Count);
// Need to remove the person from personListBox1 here
// Then move them to personListBox2
}
}
else
{
MessageBox.Show("Please select a number before trying to random.");
}
}

Answer

Maybe this?

    private void randomButton_Click(object sender, RoutedEventArgs e)
    {
        if (this.numberComboBox.SelectedIndex != -1 && Convert.ToInt16(this.numberComboBox.SelectedItem) <= personListBox.Items.Count)
        {               
            int number = Convert.ToInt16(this.numberComboBox.SelectedItem);

            for (int i = 0; i < number; i++)
            {
                int randomValue = random.Next(personListBox.Items.Count);                    
                var person =  personListBox.Items[randomValue];
                personListBox.Items.RemoveAt(randomValue);
                personListBox2.Items.Add(person);
            }
        } 
        else
        {
            MessageBox.Show("Please select a number before trying to random.");
        }
   }

Note that i added a condition to check that the chosen number is not greater than the number of persons in the first list.

Comments