开发者

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开发者_如何学C 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


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);


maybe

    Label[] labels = new Label[10];

needs to be

    Control[] labels = new Control[10];


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜