我们如何在c#中一次突出显示多个按钮

时间:2014-05-27 04:13:08

标签: c# winforms button

我在C#中开发一个winform应用程序,其中按钮名称上显示0到99之间的数字。如果我们点击一​​个特定的按钮,例如16,那个按钮的所有背面颜色从该按钮开始" 16"对于偶数而改为绿色,对于奇数则改为红色。 现在我试图一次突出显示所有偶数按钮,但不能。请帮助我如何一次突出显示所有偶数按钮。这是我的代码,并提前致谢。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // flowLayoutPanel1 is the name of the FlowLayoutPanel I used
            //
            for (int i = 0; i < 100; i++)
            {
               Button newButton = new Button();
               newButton.Height = 30;
               newButton.Width = 30;

               newButton.Name = "DynBtn" + i;
               newButton.Text = i.ToString();

               newButton.Click += newButton_Click;
               flowLayoutPanel1.Controls.Add(newButton);
           }
       }
       void newButton_Click(object sender, EventArgs e)
       {
           Button newButton = sender as Button;

           String buttonName = newButton.Name;

           int suffix = Convert.ToInt16(buttonName.Substring(6, 1));
           int start = suffix;

           for (int i = start; i < 100; i++)
           {
              Button nextButton = flowLayoutPanel1.Controls["DynBtn"+suffix] as Button;

              if (i % 2 == 0)
              {
                  nextButton.BackColor = Color.Green;
              }
              else
              {
                 nextButton.BackColor = Color.Red;
              }
              suffix++;
          }
      }
  }

2 个答案:

答案 0 :(得分:1)

试试这个......

 void newButton_Click(object sender, EventArgs e)
 {
       Button newButton = sender as Button;
       int buttonText = Convert.ToInt32( newButton.Text);
          foreach(Control c flowLayoutPanel1.Controls)
          {
              if (c is Button)
              {
                 Button newBtn = (Button)c;
                 int _val = Convert.ToInt32(newBtn.Text);
                  if(_val > buttonText)
                  {
                   if(_val % 2 == 0)
                     newBtn.BackColor = Color.Green;
                   else
                     newBtn.BackColor=Color.Red;
                  }
             }
          }
   }

答案 1 :(得分:0)

尝试以下方法。

    void newButton_Click(object sender, EventArgs e)
    {
        int start = Convert.ToInt16(((Button)sender).Name.Substring(6));

        Color c1;
        for (int i = 0; i < 100; i++)
        {
            Button nextButton = flowLayoutPanel1.Controls["DynBtn" + i] as Button;

            if (i < start)
                c1 = SystemColors.Control;
            else if (i % 2 == 0)
                c1 = Color.Green;
            else
                c1 = Color.Red;

            nextButton.BackColor = c1;
        }
    }