mac mac - 2 months ago 6
C# Question

how can I disable other buttons when i press one in windows form application c# in switch statement

I am writing below code. Please someone can tell me that here in switch statement how can I disable all other buttons when any one of them is pressed. I actually want the user to know his luck only once in this application.

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;

}

}
}
}

Answer

you can do the following to achieve this :
first set your buttons Tag property to the buttons name in your load event of the form :

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

        }

then what you want to do is iterate through your controls and disable the ones that are not the clicked one :
Note that here its considered that the buttons are not in a groupbox, if that was the case you would have to iterate through your container which would be the groupbox in that case.

 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;

            }

        }

edit: i also removed the exit button from the switch statement.