Greycrow
Greycrow

Reputation: 1633

Adding an Array of labels to a Panel

I'm trying to add an array of labels to a panel in my Form. I chose a label because I could set colors for the text. If there is a better way, please let me know.

The code below runs fine but will only display one label. I set a breakpoint and looked at the array before adding and all the elements are there.

However, only one label actually shows up on the Panel.

Here's the code.

        int y = 0;
        int index = 0;

        Label[] labels = new Label[10];

        //Add Spareboard Employees to Spare List
        foreach (Employee employee in EmployeeList)
        {
                labels[index] = new Label();

                labels[index].Text = employee.Name;

                labels[index].ForeColor = Color.Red;

                labels[index].Location = new Point(0, y);

                y = y + 10;
                ++index;
        }

        // Add the Label control to the form.
        SparePanel.Controls.AddRange(labels);

Thanks in advance

Upvotes: 1

Views: 7846

Answers (4)

BlueMonkMN
BlueMonkMN

Reputation: 25601

Another possibility (which you were also looking for) is to draw the strings directly on the UI without adding controls. Do it during the paint event of the panel.

private void SparePanel_Paint(object sender, PaintEventArgs e)
{
   using (SolidBrush empBrush = new SolidBrush(Color.Red))
   {
      int y = 0;
      foreach (Employee employee in EmployeeList)
      {
         e.Graphics.DrawString(employee.Name, ((Panel)sender).Font, empBrush, 0, y);
         y += 10;
      }
   }
}

Upvotes: 0

BlueMonkMN
BlueMonkMN

Reputation: 25601

The default size of the label is too big and each label's bottom is covering up the top of the label below it. You should add something like this:

labels[index].Size = new Size(50, 12);

Upvotes: 2

Alex
Alex

Reputation: 4934

As far as I know, you need to implement the IEnumerable Interface and IEnumerate.Compare() method too, in order to iterate a foreach loop over your Employee object.

public class Employee : IEnumerator
{

//Implement IEnumerate method here


}

I'm not that experienced though so don't take my word for it! I would put more detailed code but I don't have it to hand.

Upvotes: 0

Hogan
Hogan

Reputation: 70523

maybe

    Label[] labels = new Label[10];

needs to be

    Control[] labels = new Control[10];

Upvotes: 0

Related Questions