0

I have an array of strings, which will be placed into the text of a button, it is shuffling the array correctly but when it comes to placing the text inside of the button it is replacing them all with the same value and has no way of knownig whether the value has already been used or no t, I'm guessing this is down to the loops being in the wrong position or something of that nature.

protected void Page_Load(object sender, EventArgs e)
{

    string[] arr = new string[]
    {
        "0","1","2","3","4","5","6","7","8","9"
    };
    //shuffle code

    string[] shuffle = RandomStringArrayTool.RandomizeStrings(arr);
    foreach (string s in shuffle)
    {   
        foreach (var item in panel1.Controls)
        {
            if (item is Button)
            {  
                ((Button)item).Text = s.ToString();
            }
        }
    }


}
1
  • Is your RandomStringArrayTool class from here: dotnetperls.com/shuffle ? Commented Jan 23, 2015 at 4:32

1 Answer 1

3

yes you are calling foreach twice! it does the second foreach for all the strings of shuffleso ending with all the buttons named with the value of shuffle[9]

change it to :

int i=0;
foreach (var item in panel1.Controls)
{
    if (item is Button)
    {  
        ((Button)item).Text = shuffle[i];
        i++;
    }
}

EDIT

You can get rid of RandomStringArrayTool thing, and implement your own, this is an easy way to start of:

string str = "0123456789";
bool[] used = new bool[10];
Random r = new Random();

foreach (var item in shuffle_gbx.Controls)
{
    // keep looking for unused index
    int i = r.Next(0,10);
    while (used[i])
    {
       i = r.Next(0, 10);
    }

    ((Button)item).Text = str[i].ToString();
    used[i] = true;
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.