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

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    Of course not.. a `string` is not a `PictureBox`.. therefore, a `BackColor` property does not exist. – Simon Whitehead Sep 29 '14 at 05:34
  • No, you don't need to _access a variable by a string_. **You need an array**. – sampathsris Sep 29 '14 at 05:35
  • http://stackoverflow.com/questions/18434263/c-sharp-use-a-string-to-call-a-variable , http://stackoverflow.com/questions/20857773/create-dynamic-variable-name , http://stackoverflow.com/questions/23699542/how-can-i-access-to-all-comboboxes-by-for-loop-in-c , http://stackoverflow.com/questions/4483912/find-a-control-in-c-sharp-winforms-by-name – user2864740 Sep 29 '14 at 05:40

3 Answers3

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];
Joey
  • 344,408
  • 85
  • 689
  • 683
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;
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
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;
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92