向Panel添加标签数组

时间:2010-01-10 22:25:58

标签: c# winforms

我正在尝试向表单中的面板添加一组标签。 我选择了一个标签,因为我可以为文本设置颜色。 如果有更好的方法,请告诉我。

以下代码运行正常,但只会显示一个标签。 我设置了一个断点并在添加之前查看了数组 元素在那里。

但是,Panel上只显示一个标签。

这是代码。

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

提前致谢

4 个答案:

答案 0 :(得分:2)

标签的默认尺寸太大,每个标签的底部都覆盖在其下方标签的顶部。你应该添加这样的东西:

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

答案 1 :(得分:0)

也许

    Label[] labels = new Label[10];

需要

    Control[] labels = new Control[10];

答案 2 :(得分:0)

据我所知,你需要实现IEnumerable接口和IEnumerate.Compare()方法,以便在你的Employee对象上迭代foreach循环。

public class Employee : IEnumerator
{

//Implement IEnumerate method here


}

我不是那么有经验,所以不要相信我的话!我会提供更详细的代码,但我没有把它交给你。

答案 3 :(得分:0)

另一种可能性(您也在寻找)是直接在UI上绘制字符串而不添加控件。在面板的绘画事件期间执行此操作。

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;
      }
   }
}
相关问题