Home > database >  C# Windows Forms- How to change a single property of more than one control with the same parent?
C# Windows Forms- How to change a single property of more than one control with the same parent?

Time:06-08

Is there any way I can make it so a certain property of several controls can be changed using say, hypothetically, a FOR loop? All these controls I am mentioning have the same parent which is another panel. I've tried searching for answers but I can't find them or some of them talk about other things.

private void InitiateLargeDialogue(string title, string text1, string text2, Size size)
        {
            lblLargeTitle.Text = title;
            lblLargeText1.Text = text1;
            lblLargeText2.Text = text2;

            lblLargeText3.Visible = false; 
            lblLargeText4.Visible = false; 
            lblLargeText5.Visible = false; 
            pnlLargeExample.Visible = false;

            btnYes.Visible = false; 
            btnNo.Visible = false;
        }

Thank you!

CodePudding user response:

Honestly what you have now is what I'd expect of a WinForms project -- it's instantly readable.

However, if you'd like, you can do the following instead:

Control[] controlarray = new Control[]
{
    lblLargeText3,
    lblLargeText4,
    lblLargeText5,
    pnlLargeExample,
    btnYes,
    btnNo
}
private void InitiateLargeDialogue(string title, string text1, string text2, Size size)
{
    lblLargeTitle.Text = title;
    lblLargeText1.Text = text1;
    lblLargeText2.Text = text2;

    foreach(Control c in controlarray)
        c.Visible = false;
}

CodePudding user response:

List<Label> listLabel = new List<Label>();
public void test()
{
    listLabel.Add(new Label() { Text = "aaa" });
    listLabel.Add(new Label() { Text = "bbb" });
    listLabel.Add(new Label() { Text = "ccc" });

    int count = 1;
    foreach(Label l in listLabel)
    {
        l.Text  = $" {count  }";
        Console.WriteLine(l.Text);
    }
}

// result aaa 1 bbb 2 ccc 3

  • Related