Jonathan W

Jonathan W

  • NA
  • 3
  • 0

Select a random member of an arrayList

Jan 14 2010 6:05 PM

I have an arrayList that contains words (house, car ... whatever) and I want to display individual words from this arrayList in a label at different times when a button is clicked. So every time I click the button I want the old word in the label to disappear and a new one to appear.

I've written the following code to do this but its not working... I'm extracting the arrayList members to a string, then selecting a random member from this string...


private void btnRandomWord_Click(object sender, EventArgs e)
        {
            if (words.Count == 0)
            {
                lblRandomWord.Text = "No saved words";
            }
           
            string[] strAllWords = new string[10];

            foreach (object item in words)//words is an arrayList containing the words
            {
                for (int i = 0; i <= strAllWords.Length - 1; i++)
               
                strAllWords.SetValue(item, i);
            }
            Random RandString = new Random();

            lblRandomWord.Text = strAllWords[RandString.Next(0, strAllWords.Length)];
        }


Answers (2)