Dark warrior
Dark warrior

Reputation: 3

Clearing Labels in a Group Box by keywords contained in Label Name C# Visual Studio

I'm new to C# and visual studio. I am looking to clear some labels in a group box using a key word in label name that is common among all labels I wish to clear.

My current code is:

        foreach (Control c in BookingSummaryGroupBox.Controls)
        {
            if (c is Label)
            {
                c.Text = "";
            }
        }

But it obviously clears all labels.

Any other ways without changing control types and writing out each line to identify every individual Label to clear?

Thanks. Mark

Upvotes: 0

Views: 226

Answers (1)

cmos
cmos

Reputation: 522

I think all you need is another if-statement to check for the key word in the label name.

foreach (Control c in BookingSummaryGroupBox.Controls)
{
    if (c is label && c.Name.Contains("yourKey"))
    {
        c.Text = "";
    }
}

Also if you only want to loop through the labels within the groupbox, you could use a loop like this:

foreach (Label lbl in BookingSummaryGroupBox.Controls.OfType<Label>())
{
    if (lbl.Name.Contains("yourKey"))
    {
        lbl.Text = "";
    }
}

Upvotes: 1

Related Questions