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)];
}
Nilanka DharmadasaPosted Jan 14, 2010, 11:14 PM
The reason is when you set, words in 'words' arraylist to the array, the all the elements in the array gets filled with the last word in arraylist.
BTW you can simply write it in this way. Check this code. It works.
private void btnRandomWord_Click(object sender, EventArgs e)
{
if (words.Count == 0)
{
lblRandomWord.Text = "No saved words";
}
string[] strAllWords = (string[])words.ToArray(typeof(string));
Random RandString = new Random();
lblRandomWord.Text = strAllWords[RandString.Next(0, strAllWords.Length)];
}
Or you can simply use a code like this without using an array.
private void btnRandomWord_Click(object sender, EventArgs e)
{
if (words.Count == 0)
{
lblRandomWord.Text = "No saved words";
}
Random RandString = new Random();
lblRandomWord.Text = words[RandString.Next(0, words.Count)].ToString();
}
Please tick 'Do you like this answer' check box if you find my answer useful. It helps me.
Jonathan WPosted Jan 15, 2010, 2:21 AM