0

I want to use a string value like this

Random rnd = new Random();
int x= rnd.Next(1, 10);
string ime = "pictureBox" + x.ToString();
ime.BackColor = Color.CornflowerBlue;

but that doesnt work

3

3 Answers 3

2

You don't really want to use a string like this. You want to get a control with that name and use it like this. You can get a control by name like follows:

var pictureBox = myForm.Controls[ime];
Sign up to request clarification or add additional context in comments.

Comments

1

Following code should work for you,

Random rnd = new Random();
int x= rnd.Next(1, 10);
string ime = "pictureBox" + x.ToString();
((PictureBox)frm.Controls.Find(ime ,true)[0]).BackColor = Color.CornflowerBlue;

Comments

0

Instead of generating a random name and using it do find the PictureBox with that name, directly pick a random PictureBox:

Random rnd = new Random();
var pictureBoxes = frm.Controls.OfType<PictureBox>().ToArray();
var randomPictureBox = pictureBoxes[rnd.Next(pictureBoxes.Length)];

randomPictureBox.BackColor = Color.CornflowerBlue;

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.