我已经动态创建了一个按钮列表并将其设置为表单。单击其中一个后,其下一个按钮将显示为选中状态。
是否可以取消选择以表格形式动态创建的所有控件?特别是,我可以以某种方式在单击前一个按钮之后取消选择该按钮吗?
private void GenerateButton()
{
for (int i = 1; i <= 15; ++i)
{
for (int j = 1; j <= 25; ++j)
{
Button button = new Button();
button.Location = p;
button.Size = size;
button.BackColor = Color.RoyalBlue;
button.Padding = pad;
button.Click += new EventHandler(button_Click);
this.Controls.Add(button);
p.X += 23;
}
p.Y += 23;
p.X = 0;
}
}
protected void button_Click(object sender, EventArgs e)
{
Button but = sender as Button;
but.Enabled = false;
but.BackColor = Color.LightGray;
}
答案 0 :(得分:0)
您可以尝试此方法,该方法将在单击按钮后选择表单中的下一个按钮。您需要将此按钮事件处理程序附加到所有按钮。按钮的顺序由控件列表中的按钮顺序决定。如果需要特定的订单,则需要使用LINQ按控件的TabOrder属性对控件进行排序,并确保正确设置TabOrder
private void button_Click(object sender, EventArgs e)
{
var btn = (Control)sender;
btn.Enabled = false;
btn.BackColor = Color.LightGray;
// Where is this button in the form?
var indexOfThisButton = this.Controls.IndexOf(btn);
// Find next button index
for (int i = indexOfThisButton+1; i < this.Controls.Count; i ++)
{
// If it's a button, select it
if (this.Controls[i] is Button)
{
this.Controls[i].Select();
return;
}
}
// If we got down here we have got to the end of the controls list, start again
for (int i = 0; i < this.Controls.Count; i++)
{
// If it's a button, select it
if (this.Controls[i] is Button)
{
this.Controls[i].Select();
return;
}
}
}