In this example, we will llearn move Items from a ListBox to another in C# Windows Forms .
Make random groups of team or people from listbox and seperate them to the other listboxes.
Form Design:
In our first approach, we are going to create ListBox and Button Controls at design-time using the Forms designer.
To create a ListBox control at design-time, we simply drag a ListBox control from the Toolbox and drop it to a Form in Visual Studio. After you drag and drop a ListBox onto a Form, the ListBox looks as in Figure 1. Once a ListBox is on the Form, you can move it around and resize it using the mouse and set its properties and events.
Figure1
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace tournement { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.Text = "csharp-console-examples.com"; this.BackColor = Color.Orange; listBox1.Enabled = false; //Add Items listBox1.Items.Add("Team 1"); listBox1.Items.Add("Team 2"); listBox1.Items.Add("Team 3"); listBox1.Items.Add("Team 4"); listBox1.Items.Add("Team 5"); listBox1.Items.Add("Team 6"); listBox1.Items.Add("Team 7"); listBox1.Items.Add("Team 8"); listBox1.Items.Add("Team 9"); listBox1.Items.Add("Team 10"); listBox1.Items.Add("Team 11"); listBox1.Items.Add("Team 12"); listBox1.Items.Add("Team 13"); listBox1.Items.Add("Team 14"); listBox1.Items.Add("Team 15"); listBox1.Items.Add("Team 16"); } private void button1_Click(object sender, EventArgs e) { Random rnd = new Random(); int countTeam = listBox1.Items.Count; for (int i = 1; i <= countTeam; i++) { int slctdTeam = rnd.Next(0, listBox1.Items.Count); if (i % 2 == 1) { listBox2.Items.Add(listBox1.Items[slctdTeam]); listBox1.Items.RemoveAt(slctdTeam); } else { listBox3.Items.Add(listBox1.Items[slctdTeam]); listBox1.Items.RemoveAt(slctdTeam); } } } } } |
Output: