tags:

views:

103

answers:

3

Hi,

I have a winforms app and the main (and only) form has several buttons. When the user clicks a button, I want all other buttons to be disabled.

I know I could do this the long way by setting "Enabled" to false on all buttons but the one which has been clicked in the clicked event handler of that button, but this is a long and tedious approach.

I got the collection of controls on the form, but this does not include the several buttons I have:

        System.Windows.Forms.Control.ControlCollection ctrls = this.Controls;

How can I go about implementing this functionality in a mantainable fashion?

Thanks

A: 
DisableControls(Control c)
{
    c.Enable  = false;
    foreach(Control child in c.Controls)
       DisableControls(child)
}
Alex Reitbort
Thanks! I see I missed out the recursion trick.
csharpdev
Careful, this will disable everything, not just buttons!
Philip Wallace
A: 
private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control ctrl in this.Controls)
    {
        if (ctrl is Button)
        {
            Button btn = (Button)ctrl;
            btn.Click += ButtonClick;
        }
    }

}

private void ButtonClick(object sender, EventArgs e)
{
    foreach (Control ctrl in this.Controls)
    {
        if (ctrl is Button)
        {
            Button btn = (Button)ctrl;
            if (btn != (Button)sender)
            {
                btn.Enabled = false;
            }
        }
    }
}
MusiGenesis
A: 

You could use databinding, so you only iterate once on startup:

public partial class Form1 : Form
{
    public bool ButtonsEnabled { get; set; }

    public Form1()
    {
        InitializeComponent();

        // Enable by default
        ButtonsEnabled = true;

        // Set the bindings.
        FindButtons(this);
    }

    private void button_Click(object sender, EventArgs e)
    {
        // Set the bound property
        ButtonsEnabled = false;

        // Force the buttons to update themselves
        this.BindingContext[this].ResumeBinding();

        // Renable the clicked button
        Button thisButton = sender as Button;
        thisButton.Enabled = true;
    }

    private void FindButtons(Control control)
    {
        // If the control is a button, bind the Enabled property to ButtonsEnabled
        if (control is Button)
        {
            control.DataBindings.Add("Enabled", this, "ButtonsEnabled");
        }

        // Check it's children
        foreach(Control child in control.Controls)
        {
            FindButtons(child);
        }
    }
}
Philip Wallace