A
A
Andrey Begin2018-08-27 16:13:44
C++ / C#
Andrey Begin, 2018-08-27 16:13:44

How to put things in order in c# code?

What is the alternative to this piece of code?
For example, using a simple loop?

label24.Visible = false;
            label25.Visible = false;
            label26.Visible = false;
            label27.Visible = false;
            label28.Visible = false;
            label29.Visible = false;
            label30.Visible = false;
            label32.Visible = false;
            label33.Visible = false;
            label34.Visible = false;
            label35.Visible = false;
            label36.Visible = false;
            label37.Visible = false;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LiptonOlolo, 2018-08-27
@MoVVe

2 simplest options:

public partial class Form1 : Form
{
  List<Label> Labels { get; }

  public Form1()
  {
    InitializeComponent();

    //1 Вариант: Коллекция со всеми нужными лейблами.

    //Обратите внимание, что используются сами КОНТРОЛЫ, а НЕ их ИМЕНА.
    Labels = new List<Label> { label1, label2, label3, label4, label5, label6, label7, label8, label9, label10, label11, label12, label13, label14, label15, label16 };

    Labels.ForEach(x => x.Visible = true);
    Labels.ForEach(x => x.Visible = false);

    //2 Вариант: Перебор ВСЕХ(!) контролов на форме.

    foreach (var item in Controls)
      if (item is Label)
        ((Label)item).Visible = true;

    foreach (var item in Controls)
      if (item is Label)
        ((Label)item).Visible = false;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question