如何禁用click事件处理程序中除一个按钮之外的所有按钮?

时间:2016-09-18 16:44:31

标签: c# winforms

我正在编写下面的代码。请有人告诉我,在switch语句中,当按下任何一个按钮时,如何禁用所有其他按钮。我实际上希望用户在这个应用程序中只知道他的运气一次。

  namespace tryAppWFA
   {
      public partial class mainWindow : Form
       {
    public mainWindow()
    {
        InitializeComponent();
    }

    private void button_click(object sender, EventArgs e)
    {
        Button button=(Button)sender;
       switch (button.Name) { 
            case "button1":
               textBox.Text = "Hey ! you may get a car after one year";

               break;
            case "button2":
    textBox.Text = "Hey ! you may get a big super duper House after a year";
                break;
            case "button3":
                textBox.Text = "something";
                break;
            case "button4":
                textBox.Text = "something";
                break;
            case "button5":
                textBox.Text = "somehting"
                break;
           case "exit":
                Environment.Exit(0);
                break;
           default:
            break;

        }

       }
      }
      }

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作来实现此目的:
首先将按钮Tag属性设置为表单加载事件中的按钮名称:

private void MainForm_Load(object sender, EventArgs e)
{
    button1.Tag = button1.Name;
    button2.Tag = button2.Name;
    btnExit.Tag = btnExit.Name;
    //and so on...

}

那么你想要做的就是遍历你的控件并禁用那些不是被点击的控件:
请注意,此处认为按钮不在组框中,如果是这种情况,则必须遍历您的容器,在这种情况下将是组框。

private void button5_Click(object sender, EventArgs e)
{
    foreach (Button item in this.Controls.OfType<Control>().Where(c => c.GetType() == typeof(Button)))
    {
        if (item.Name == btnExit.Name)
            continue;
        item.Enabled = false;
    }
    Button button = (Button)sender;
    switch (button.Name)
    {
        case "button1":
            textBox.Text = "Hey ! you may get a car after one year";
            break;
        case "button2":
            textBox.Text = "Hey ! you may get a big super duper House after a year";
            break;
        case "button3":
            textBox.Text = "something";
            break;
        case "button4":
            textBox.Text = "something";
            break;
        case "button5":
            textBox.Text = "somehting";
             break;
        default:
            break;
    }
}

编辑:我还从switch语句中删除了退出按钮。