0

I'm quite new to coding in c# and i'm having difficulty assigning properties to a random textbox from an array. Here is the code i am using:

TextBox[] peopletiles = { A2, A3, A4, A5,};
int totalpeople = 0; 

do
{
    Random random = new Random();
    int tile = random.Next(0, peopletiles.Length);
    tile.BackColor = Color.Purple;                    
    totalpeople += 1;
} while (totalpeople != Edit.peopleStart);                    

I'm trying to change the colour of a random textbox from the array "peopletiles" to purple and have this looped until the number of purple text boxes is equal to the value of "Edit.peopleStart"

Using the code above gives the error "'int' does not contain a definition for 'BackColor'"

2
  • You should describe the actual problem you're seeing (expected values vs. actual values) Commented Jan 13, 2019 at 17:51
  • The problem is that you're declaring a new Random() inside your loop. Random is seeded by the system clock, so when instantiated in a hard loop, it will produce the same number for quite a few iterations. Try moving the Random random = new Random(); before the do loop. Commented Jan 13, 2019 at 17:52

2 Answers 2

1

You are trying to set a property of an int, not of a textbox in this code:

int tile = random.Next(0, peopletiles.Length);
tile.BackColor = Color.Purple; 

You want to try

var tile = peopletiles[random.Next(0, peopletiles.Length)];
tile.BackColor = Color.Purple; 

Also, as remarked in a comment, you should not create a new Random() in your loop, but outside it (or even on Class level, just once)

Sign up to request clarification or add additional context in comments.

Comments

1

Take your random variable outside the loop, that is important when you use Random. Also you need to modify your loop a little bit. Use List instead and on each iteration choose random TextBox, change color and remove it from temporary list.

using System.Collections.Generic;

var peopletiles = new List<TextBox>{ A2, A3, A4, A5,};
Random random = new Random();
for (var i = 0; i < Edit.peopleStar; i++)
{
    var index = random.Next(0, peopletiles.Length);
    peopletiles[index].BackColor = Color.Purple;
    peopletiles.RemoveAt(index);
}

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.