Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to assign the visibility for multiple controls

Tags:

arrays

c#

boolean

OK so i'm trying to clean up my code because it is a mess and what i have is 25 richtext boxes and i want to put their .Visible variable into an array and have a for statement go through and make each false so that the text box doesn't show up what i have tried hasn't worked and i can't figure it out what i have is.

bool[] box =  new bool[25];

box[0] = richTextBox1.Visible;
box[1] = richTextBox2.Visible;
box[2] = richTextBox3.Visible;
box[3] = richTextBox4.Visible;
box[4] = richTextBox5.Visible;
box[5] = richTextBox6.Visible;
box[6] = richTextBox7.Visible;
box[7] = richTextBox8.Visible;
box[5] = richTextBox6.Visible;
box[6] = richTextBox7.Visible;
box[7] = richTextBox8.Visible;
box[8] = richTextBox9.Visible;
box[9] = richTextBox10.Visible;
box[10] = richTextBox11.Visible;
box[11] = richTextBox12.Visible;
box[12] = richTextBox13.Visible;
box[13] = richTextBox14.Visible;
box[14] = richTextBox15.Visible;
box[15] = richTextBox16.Visible;
box[16] = richTextBox17.Visible;
box[17] = richTextBox18.Visible;
box[18] = richTextBox19.Visible;
box[19] = richTextBox20.Visible;
box[20] = richTextBox21.Visible;
box[21] = richTextBox22.Visible;
box[22] = richTextBox23.Visible;
box[23] = richTextBox24.Visible;
box[24] = richTextBox25.Visible;

for(int y = 0; y <25; y++)
  {
    box[y] = false;
  }
like image 921
user3448117 Avatar asked Dec 02 '22 20:12

user3448117


1 Answers

You canot change the bool in the array and expect that that changes the Visible state of the TextBoxes.

You have to change that property. Therefore you either have to store these controls in a collection or use a different approach: If they are in the same container control (like Form, GroupBox, Panel etc.) you could use Enumerable.OfType.

For example:

var allRichTextBoxes = this.Controls.OfType<RichTextBox>()
    .Where(txt => txt.Name.StartsWith("richTextBox"));
foreach(var rtb in allRichTextBoxes)
    rtb.Visible = false;
like image 138
Tim Schmelter Avatar answered Dec 11 '22 10:12

Tim Schmelter