如何在c#中一次高亮显示多个按钮?
本文关键字:显示 高亮 一次 按钮 | 更新日期: 2023-09-27 18:05:22
我正在开发一个c#中的winform应用程序,其中从0到99的数字显示在按钮名称上。如果我们点击一个特定的按钮,比如16,所有从该按钮"16"开始的按钮的Back Color都会改变,比如绿色代表偶数,红色代表奇数。现在我试着一次突出所有偶数的按钮,但不能。请帮助我如何才能突出所有偶数按钮在一个时间。这是我的代码和提前感谢。
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++;
}
}
}
try this…
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;
}
}
}
}
尝试以下方法。
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;
}
}