在 C# 中计算按钮的颜色

本文关键字:颜色 按钮 计算 | 更新日期: 2023-09-27 18:31:19

我的程序有问题。我有 3 个按钮,默认颜色为白色。当我的按钮背面颜色变为红色时,我的程序将计算有多少按钮是红色的。我有一个想法可以使用foreach,但它不起作用

Button[] Tombol = new Button[]{B1, B2, B3}
int counterbutton = 0;
foreach (Button Tombol2.BackColor = Color.Red in Tombol) //I have problem here. I don't know how to solve
{
  counterbutton++;
}

在 C# 中计算按钮的颜色

我认为正确的语法是;

foreach(Button btn in Tombol)
{
    if(btn.BackColor == Color.Red)
       counterbutton++;
}
foreach(Button b in Tombol)
{
    if(b.BackColor == Color.Red)
        counterbutton++;
}

一个带有 linq 的示例:

var counter = Tombol.Count(b=>b.BackColor == Color.Red)
Button[] Tombol = new Button[]{B1, B2, B3}
int counterbutton = 0;
foreach (Button btn in Tombol) //I have problem here. I don't know how to solve
{
  if(btn.BackColor == Color.Red)
  counterbutton++;
}

试试这个

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Button[] Tombol = new Button[]{B1, B2, B3};
            int counterbutton = 0;
            B1.BackColor = Color.Red;
            B3.BackColor = Color.Red;
            foreach (Button b in Tombol)
            {
                if(b.BackColor == Color.Red) //I have problem here. I don't know how to solve
                {
                    counterbutton++;
                }
            }
        }
    }
}