How to randomly reorder an ArrayList and refresh the ComboBox contents at runtime

Posted by: Suprotim Agarwal , on 6/3/2008, in Category WinForms & WinRT
Views: 36115
Abstract: In this short snippet, we will take a look at how to randomly reorder an array using an ArrayList.
How to randomly reorder an ArrayList and Refresh the ComboBox contents at Runtime
 
In this short snippet, we will take a look at how to randomly reorder an arraylist and update the contents of the ComboBox each time the contents of the ArrayList changes. This article has been republished.
Note : If anyone is interested in the VB.NET version of this code, it is given at the end of this article.
Step 1: Drag and drop a combobox and a button on your form.
Step 2: Declare an ArrayList at the form level
C#
ArrayList l = new ArrayList();  
Step 3: In the Form_Load(), add items to the ArrayList
C#
private void Form1_Load(object sender, EventArgs e)
{
       l.Add("Jack");
       l.Add("Jim");
       l.Add("Harry");
      l.Add("Zane");
      l.Add("Sally");
       RandomOrder(l);
}
 
 
Step 4: Create a function called RandomOrder
 
C#
public void RandomOrder(ArrayList arrList)
        {
            Random r = new Random();
            for (int cnt = 0; cnt < arrList.Count; cnt++)
            {
                object tmp = arrList[cnt];
                int idx = r.Next(arrList.Count - cnt) + cnt;
                arrList[cnt] = arrList[idx];
                arrList[idx] = tmp;
            }
           
        }
 
The logic is as follows. This function accepts an arraylist. Then a random element is picked up and added at position 0. Another random element is picked where postion <> 0 and swapped into position 1 and then another random element is picked where position <> 0 or 1 and swapped it into position 2 and so on…
 
Step 5: Now we will add some code to update the combobox each time the arraylist is updated. ArrayList belongs to the type Ilist. If your control is bound to a data source that does not implement the IBindingList interface, such as an ArrayList then changes to the list will NOT reflect as changes in the combobox. So for that, we will use this code to update the ComboBox each time the arraylist changes :
C#
 
BindingManagerBase bindMB = comboBox1.BindingContext[arrList];
bindMB.SuspendBinding();
bindMB.ResumeBinding();
comboBox1.DataSource = arrList;
 
As you see, suspending and resuming the binding process  forces the combobox to be updated manually.
 
Step 6: Call the RandomOrder() method on the click event of the button
 
C#
privatevoid button1_Click(object sender, EventArgs e)
{
     RandomOrder(l);
}
 
And that’s it.
 
The entire code looks like this :
 
C#
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
 
namespace WindowsApplication1
{
    publicpartialclassForm1 : Form
    {
        ArrayList l = newArrayList();       
 
        public Form1()
        {
            InitializeComponent();
        }
 
        privatevoid Form1_Load(object sender, EventArgs e)
        {
            l.Add("Jack");
            l.Add("Jim");
            l.Add("Harry");
            l.Add("Zane");
            l.Add("Sally");
            RandomOrder(l);
        }
 
        publicvoid RandomOrder(ArrayList arrList)
        {
            Random r = newRandom();
            for (int cnt = 0; cnt < arrList.Count; cnt++)
            {
                object tmp = arrList[cnt];
                int idx = r.Next(arrList.Count - cnt) + cnt;
                arrList[cnt] = arrList[idx];
                arrList[idx] = tmp;
            }
 
            BindingManagerBase bindMB = comboBox1.BindingContext[arrList];
            bindMB.SuspendBinding();
            bindMB.ResumeBinding();
            comboBox1.DataSource = arrList;
           
        }
 
        privatevoid comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
 
        }
 
        privatevoid button1_Click(object sender, EventArgs e)
        {
            RandomOrder(l);
        }
 
    }
}
 
 
VB.NET
 
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Collections
 
Namespace WindowsApplication1
          PublicPartialClass Form1
                   Inherits Form
                   Private l As ArrayList = New ArrayList()
 
                   PublicSubNew()
                             InitializeComponent()
                   EndSub
 
                   PrivateSub Form1_Load(ByVal sender AsObject, ByVal e As EventArgs)
                             l.Add("Jack")
                             l.Add("Jim")
                             l.Add("Harry")
                             l.Add("Zane")
                             l.Add("Sally")
                             RandomOrder(l)
                   EndSub
 
                   PublicSub RandomOrder(ByVal arrList As ArrayList)
                             Dim r As Random = New Random()
                             For cnt AsInteger = 0 To arrList.Count - 1
                                      Dim tmp AsObject = arrList(cnt)
                                      Dim idx AsInteger = r.Next(arrList.Count - cnt) + cnt
                                      arrList(cnt) = arrList(idx)
                                      arrList(idx) = tmp
                             Next cnt
 
                             Dim bindMB As BindingManagerBase = comboBox1.BindingContext(arrList)
                             bindMB.SuspendBinding()
                             bindMB.ResumeBinding()
                             comboBox1.DataSource = arrList
 
                   EndSub
 
                   PrivateSub comboBox1_SelectedIndexChanged(ByVal sender AsObject, ByVal e As EventArgs)
 
                   EndSub
 
                   PrivateSub button1_Click(ByVal sender AsObject, ByVal e As EventArgs)
                             RandomOrder(l)
                   EndSub
 
          EndClass
EndNamespace
 
 
References :
 
 
 
 
Conclusion: There are numerous ways of reordering an arraylist. I just demoed one of them. You could also use the Generic collection to do so. Try it out!!. I hope this article was useful and I thank you for viewing it.
 
If you liked the article,  Subscribe to my RSS Feed. 
 
 
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Greg Beech on Friday, January 11, 2008 3:35 AM
Or even easier:

Random r = new Random();
Array.Sort(someArray, () => r.Next(-1, 1));
Comment posted by Suprotim Agarwal on Friday, January 11, 2008 9:14 AM
Hi Greg, Thanks for the code.
Comment posted by ramesh on Tuesday, June 10, 2008 1:25 AM
valuelabs
Comment posted by max on Friday, September 19, 2008 8:13 AM
really stupid article!
Comment posted by Deniz Cakir on Monday, December 22, 2008 12:20 PM
You can use the same logic with Datasets.
DataSet1TableAdapters.someTableAdapter dta = new WindowsFormsApplication5.DataSet1TableAdapters.someTableAdapter();
BindingManagerBase bindMB = comboBox1.BindingContext[dataSet1.some];
bindMB.SuspendBinding();
bindMB.ResumeBinding();
comboBox1.DataSource = dta.GetData();
Thanks for the idea.
Comment posted by Suprotim Agarwal on Friday, December 26, 2008 9:11 PM
Thanks Deniz

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook