user1925801
user1925801

Reputation: 154

Making labels in array change backcolor on click using C# in Windows Forms

How can I change the BackColor of a label in an array when I click on it? Since there are multiple elements, I cannot manually activate each event for each individual label.

for (int i = 0; i < 361; i++)
        {
            board[i] = new Label();
            board[i].Parent = pictureBox1;
            board[i].Location = new Point(x, y);
            board[i].Name = "label" + i;
            board[i].BackColor = Color.Black;
            //set size of labels
            board[i].Size = new Size(30, 30);
            //initialize click event handler
            this.board[i].Click += new System.EventHandler(this.labelClick);

        }

private void labelClick (object sender, EventArgs e)
        {
            foreach (Label i in board)
            {
                if (iteration % 2 == 0)
                {
                    i.BackColor = Color.Black;
                    iteration++;
                }
                else if(iteration % 2 == 1)
                {
                    i.BackColor = Color.White;
                    iteration++;
                }
            }
        }

Upvotes: 1

Views: 439

Answers (2)

Darren H
Darren H

Reputation: 460

There are a few ways you can handle this. One way is to wire each Labels Click event up to the same event:

this.label1.Click += new System.EventHandler(this.label_Click);
this.label2.Click += new System.EventHandler(this.label_Click);
this.label3.Click += new System.EventHandler(this.label_Click);

In the label_Click event you can set the BackColor of each label OR just the one you clicked on.

// This will set each label's BackColor to Red.
private void label_Click(object sender, EventArgs e)
{
    foreach (Label label in labelArray)
    {
        label.BackColor = Color.Red;
    }
}

// This will set just the clicked on Label's BackColor to Red.
private void label_Click(object sender, EventArgs e)
{
    Label label = sender as Label;
    if (label != null)
    {
        label.BackColor = Color.Red;
    }
}

Upvotes: 1

Colin Grealy
Colin Grealy

Reputation: 615

var labels = new[] 
{
    // labels here
};

foreach (var label in labels)
{
    label.Click += (sender, args) =>
       {
           var lbl = sender as Label;
           Debug.Assert(lbl != null);
           lbl.BackColour = Colors.Pink;
       };
}

Upvotes: 0

Related Questions