【问题标题】:Changing all Button background except button clicked更改除单击按钮之外的所有按钮背景
【发布时间】:2013-01-05 18:00:17
【问题描述】:

我正在处理一个有很多按钮的表单。当用户单击一个按钮时,背景应该会改变颜色。如果他们点击表单上的另一个按钮,它的背景应该会改变颜色,而之前的按钮颜色应该会恢复到原来的颜色。

我可以通过在每个按钮中硬编码来做到这一点,但是这个表单有很多按钮。我确信必须有一种更有效的方法来做到这一点

目前为止有这个

foreach (Control c in this.Controls)
{
    if (c is Button)
    {
        if (c.Text.Equals("Button 2"))
         {
             Btn2.BackColor = Color.GreenYellow;
         }
         else
         {

         }
    }
}

我可以让 Btn2 改变背景。我将如何更改表单中所有其他按钮的背景。任何想法我可以如何做到这一点而不必对每个按钮进行硬编码。

【问题讨论】:

  • 你在 else 中尝试过 c.BackColor 吗?

标签: c# winforms buttonclick


【解决方案1】:

只要您没有任何控制容器(例如面板),这将起作用

foreach (Control c in this.Controls)
{
   Button btn = c as Button;
   if (btn != null) // if c is another type, btn will be null
   {
       if (btn.Text.Equals("Button 2"))
       {
           btn.BackColor = Color.GreenYellow;
       }
       else
       { 
           btn.BackColor = Color.PreviousColor;
       }
   }
}

【讨论】:

    【解决方案2】:

    下面的代码将在不考虑表单上的按钮数量的情况下工作。只需将button_Click 方法设置为所有按钮的事件处理程序。当你点击一个按钮时,它的背景会改变颜色。当您单击任何其他按钮时,该按钮的背景将改变颜色,并且先前着色的按钮的背景将恢复为默认背景颜色。

    // Stores the previously-colored button, if any
    private Button lastButton = null;
    

    ...

    // The event handler for all button's who should have color-changing functionality
    private void button_Click(object sender, EventArgs e)
    {
        // Change the background color of the button that was clicked
        Button current = (Button)sender;
        current.BackColor = Color.GreenYellow;
    
        // Revert the background color of the previously-colored button, if any
        if (lastButton != null)
            lastButton.BackColor = SystemColors.Control;
    
        // Update the previously-colored button
        lastButton = current;
    }
    

    【讨论】:

      【解决方案3】:

      如果您的按钮位于面板内,请在 foreach 中执行以下代码 您将获得 pnl2Buttons 面板内的所有按钮,然后尝试传递要更改背景的按钮的文本名称 其余的将具有 SeaGreen 颜色。

      foreach (Button oButton in pnl2Buttons.Controls.OfType<Button>())
      {
         if (oButton.Text == clickedButton)
         {
             oButton.BackColor = Color.DodgerBlue;
         }
         else
         {
             oButton.BackColor = Color.SeaGreen;
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-15
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 2017-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多