【问题标题】:How to get all buttons and labels under splitContainer.Panel2如何获取 splitContainer.Panel2 下的所有按钮和标签
【发布时间】:2013-09-01 19:06:03
【问题描述】:

我想获取 splitContainer.Panel2 下所有按钮和标签的背景颜色。 当我尝试它时,我发现我没有成功在任何控件上运行(在 Panel2 下) 我试试这段代码:

foreach (Control c in ((Control)splitContainer.Panel2).Controls)
{
    if ((c is Button) || (c is Label))
        MessageBox.Show("Name: " + c.Name + "  Back Color: " + c.BackColor);
}

如何获取 splitContainer.Panel2 下所有标签和按钮的所有背景颜色?

编辑:

  1. 我在 splitcontainer.Panel2 中有一些面板,按钮和标签在面板中。
  2. 我只收到这条消息:“名称:panel_Right Back Color: Color [Transparent]”

【问题讨论】:

  • 在您显示的代码中什么不起作用?你有例外吗? .Controls 是否为空?
  • 那么您对此有何期待?
  • 我认为您在splitContainer.Panel2 中有一个名为panel_Right 的小组。这可能是您添加的唯一控件。让我在里面休息panel_Right
  • @Sriram Sakthivel:谢谢!你是对的。这都是我的错。但是我仍然没有成功获得所有这些,因为我在“panel_right”中有一些面板

标签: c# winforms controls splitcontainer


【解决方案1】:

您收到该消息可能是因为您的splitContainer.Panel2 下有一个面板并且应该这样做:

foreach (Control c in ((Control)splitContainer.Panel2).Controls)
{
    if(c is Panel)
    {
      foreach (Control curr in c.Controls)
      {
         MessageBox.Show("Name: " + curr.Name + "  Back Color: " + curr.BackColor);
      }
    }
}

【讨论】:

    【解决方案2】:

    你可以不用LINQ,但我想在这里使用LINQ

    public IEnumerable<Control> GetControls(Control c){            
      return new []{c}.Concat(c.Controls.OfType<Control>()
                                        .SelectMany(x => GetControls(x)));
    }    
    foreach(Control c in GetControls(splitContainer.Panel2).Where(x=>x is Label || x is Button))
       MessageBox.Show("Name: " + c.Name + "  Back Color: " + c.BackColor);
    

    【讨论】:

      【解决方案3】:

      您还应该检查ButtonLabel。在messagebox之前添加这一行:

      if ((c is Button) || (c is Label))
      

      【讨论】:

      • 谢谢。但我仍然没有成功去获取按钮或标签的任何实例。我插入这个作为代码。
      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多