Adding the value (integer) of a variable to a control name (PictureBox) in Windows Forms?

All my picture box controls are named the same beside the number at the end. Since I made it this way, is it possible to match an int value to the end of the PictureBox name and save copy/pasting some code?

My code
https://i.stack.imgur.com/jyHS5.png

>Solution :

Two ways to do this:

One way is to create an array and index into that instead

var controls = new Control[] { soldOutPB1, soldOutPB2, soldOutPB3 };

controls[index].Visible = true;

Another way is to use the controls collection and specify the control name as a string:

var control = this.Controls[$"soldOutPB1{index}"].Visible = true;

Leave a Reply