Home > Software engineering >  How can i take data from Listbox and split into 2 different listboxes?
How can i take data from Listbox and split into 2 different listboxes?

Time:04-14

I am currently trying to make a random team generator as a project. i have a Win form which have a textbox and an add button to add the text into a listbox.

I also have a Generate button, which are suppose to take the names from Listbox3 and split them randomly to Listbox1 and Listbox2.

I am stuck on the last part of getting the names from Listbox3 and split into randomly to the listbox1 and listbox2.

this is my code so far:

    private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void button3_Click(object sender, EventArgs e)
    {
        Application.Exit();
        

    }

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Select();
        listBox3.Items.Add(textBox1.Text);
        textBox1.Text = "";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        
        //*Here i need some code to take listbox3 and randomly split the list into 2 teams (Listboxt1 & Listbox2).

    }
}

Here is how the form looks with information of what is what:

https://i.stack.imgur.com/gveAB.jpg

CodePudding user response:

The following first off uses decent control names. Code splits a list into two and clears the available members from the available listbox so the end result is two team list boxes are populated.

// get available members, assumes there are enough to work with
// consider adding proper assertion
var membersList = AvailableTeamMembersListBox.Items.OfType<string>().ToList();

var random = new Random();
var numberRequired = membersList.Count / 2;

var team1 = new List<string>();
var team2 = new List<string>();

// add a member to first team, remove from current items in ListBox
for (var index = 0; index < numberRequired; index  )
{
    var nextIndex = random.Next(membersList.Count);
    team1.Add(membersList[nextIndex]);
    membersList.RemoveAt(nextIndex);
}

// remaining items in ListBox go into second list
team2.AddRange(membersList);
// clear because they have been used in the two list
membersList.Clear();

Team1ListBox.DataSource = team1;
Team2ListBox.DataSource = team2;

CodePudding user response:

You can try this:

var listBoxIndex = 0;
var listBoxes = new[] { this.listBox1, this.listBox2 };

var random = new Random();
while (listBox3.Items.Count > 0)
{
    var index = random.Next(0, listBox3.Items.Count);
    var item = listBox3.Items[index];
    listBox3.Items.RemoveAt(index);

    var listBox = listBoxes[listBoxIndex   % 2];
    listBox.Items.Add(item);
}

You save into a list (listBoxes) your 2 teams listboxes and use listBoxIndex to choose one and other in each iteration.

In each iteration, you get a random item in your source listbox, remove from the list and put in the selected team listbox.

  •  Tags:  
  • c#
  • Related