2016-01-20 71 views
0

我在程序中遇到問題。我有3個按鈕,默認顏色是白色。當我的按鈕後退顏色變成紅色時,我的程序會計算出有多少按鈕是紅色的。我有一個主意,用的foreach,但它不工作C#中的計數按鈕的顏色#

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++; 
} 
+0

什麼是'Tombol2'的方式? –

+0

Tombol2是Button [] Tombol中的所有按鈕:) –

回答

5

我覺得語法;

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

感謝您的回答。它的作品:) –

0
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++; 
} 
1
foreach(Button b in Tombol) 
{ 
    if(b.BackColor == Color.Red) 
     counterbutton++; 
} 
+0

感謝您的回答。有用 :) –

0

試試這個

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++; 
       } 
      } 
     } 
    } 
} 
1

與LINQ的爲例:

var counter = Tombol.Count(b=>b.BackColor == Color.Red)