我正在处理一个有很多按钮的表单。当用户单击一个按钮时,背景应该改变颜色。如果他们点击表单上的另一个按钮,其背景应该改变颜色,之前的按钮颜色应该返回原始颜色。
我可以通过在每个按钮中进行硬编码来完成此操作,但这种形式有很多按钮。我相信必须有一种更有效的方法来做到这一点
到目前为止我有这个
foreach (Control c in this.Controls)
{
if (c is Button)
{
if (c.Text.Equals("Button 2"))
{
Btn2.BackColor = Color.GreenYellow;
}
else
{
}
}
}
我可以获得Btn2改变的背景。我如何更改表单中所有其他按钮的背景。任何想法我怎么能这样做而不必硬编码每个按钮。
答案 0 :(得分:4)
以下代码无需考虑表单上的按钮数量即可运行。只需将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;
}
答案 1 :(得分:0)
只要您没有任何控制容器(例如面板)
,这将有效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;
}
}
}