Search code examples
c#winformsdynamic-variables

How to access a Control variable by a string?


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


Solution

  • 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;