【问题标题】:Adding an Array of labels to a Panel将标签数组添加到面板
【发布时间】:2010-01-10 22:25:57
【问题描述】:

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

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

但是,面板上实际上只显示了一个标签。

这是代码。

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

提前致谢

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    标签的默认尺寸太大,每个标签的底部都覆盖了它下面的标签顶部。您应该添加如下内容:

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

    【讨论】:

      【解决方案2】:

      也许

          Label[] labels = new Label[10];
      

      需要

          Control[] labels = new Control[10];
      

      【讨论】:

      • 如果我将其定义为控件,也会发生同样的事情
      【解决方案3】:

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

      public class Employee : IEnumerator
      {
      
      //Implement IEnumerate method here
      
      
      }
      

      虽然我没有那么有经验,所以不要相信我的话!我会放更详细的代码,但我手头没有。

      【讨论】:

      • 我把 foreach 循环拿出来,只是测试了一个简单的案例。我遇到了同样的问题,只有一个出现。 for (int i = 1; i
      • MSDN 说的以下内容,很可能适用于您: 继承者注意事项:在派生类中重写 AddRange 时,请务必调用基类的 AddRange 方法以确保将控件添加到集合中. msdn.microsoft.com/en-us/library/…
      【解决方案4】:

      另一种可能性(您也在寻找)是直接在 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;
            }
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-03-01
        • 1970-01-01
        • 2013-05-06
        • 2011-05-23
        • 2010-11-25
        • 2021-05-18
        • 1970-01-01
        • 2012-01-08
        相关资源
        最近更新 更多