Reputation: 651
I have 4 buttons and I want to disabled them if some one is clicked
Note: Only one can be disabled at a time
So my logic is like:
In btn1
Click event I do:
btn1.Enabled = false;
btn2.Enabled = true;
btn3.Enabled = true;
btn4.Enabled = true;
In btn2
click event:
btn1.Enabled = true;
btn2.Enabled = false;
btn3.Enabled = true;
btn4.Enabled = true;
And same for other 2 buttons. When I see this code I don't like it so much. Is there any way todo something more readable and short to do this type of actions
Upvotes: 2
Views: 799
Reputation: 35
private void btn_Click(object sender, EventArgs e)
{
foreach(Button btn in Controls.OfType<Button>())
btn.Enabled = true;
Button button = sender as Button;
button.Enabled = false;
}
dont forget to use System.Linq
Upvotes: 0
Reputation: 837
I'd be inclined to make the Button_Click a little less specific with the use of the some sort of data structure to control the buttons that you would like to group.
public partial class Form1 : Form
{
// Control the buttons.
List<Button> buttons = new List<Button>();
public Form1()
{
InitializeComponent();
buttons.Add(this.button1);
buttons.Add(this.button2);
buttons.Add(this.button3);
buttons.Add(this.button4);
}
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
foreach (var b in buttons)
{
if (button.Text.Equals(b.Text))
{
b.Enabled = false;
}
else
{
b.Enabled = true;
}
}
}
}
Upvotes: 1
Reputation: 8176
Here is another idea for you - you can have one handler for all buttons like this:
An your code become very straightforward:
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_click(object sender, EventArgs e)
{
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
Button btn = sender as Button;
if (btn != null)
{
btn.Enabled = false;
}
}
}
}
I hope it helps 😊
Upvotes: 3
Reputation: 119186
Rather than write lots of code, it's much simpler to use a RadioButton
group and set the Appearance
property to Button
.
As the docs suggest, this gives the radio buttons the appearance of a Windows button.
Upvotes: 3