tags:

views:

40

answers:

4

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

A: 

maybe

    Label[] labels = new Label[10];

needs to be

    Control[] labels = new Control[10];
Hogan
Same thing happens if I define it as a control
Greycrow
A: 

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.

AlexW
I took the foreach loop out and just tested a simple case.I get the same issue of only one showing up.for (int i = 1; i < 10; i++) { labels[index] = new Label(); labels[index].Text = "Test"; labels[index].ForeColor = Color.Red; labels[index].Location = new Point(0, y); y = y + 10; ++index; }
Greycrow
MSDN says the following, may well apply to you:Notes to Inheritors:When overriding AddRange in a derived class, be sure to call the base class's AddRange method to ensure that the controls are added to the collection.http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.addrange.aspx
AlexW
+1  A: 

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);
BlueMonkMN
Thanks so much!
Greycrow
A: 

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;
      }
   }
}
BlueMonkMN