Home > database >  Disable buttons in C # WinForms
Disable buttons in C # WinForms

Time:12-20

If you want to deactivate some buttons using another button

private void bdesactivar_Click(object sender, EventArgs e)
        {
             button1.Enabled = false
             button2.Enabled = false
             button3.Enabled = false
        }

But if I want to do the same with many more buttons at the same time, is there a way to optimize that function by deactivating a group of buttons, without deactivating all the buttons on my form?

CodePudding user response:

You've got a few options here, but it seems like the most fundamental issue you have here is not wanting to have to turn off buttons one by one by setting the enabled property.

Really, you could do with a function that takes a list of buttons and activates or de-activates.

private ToggleButtons(IList<Button> buttons
{
  foreach (var button in buttons){
    button.Enabled = (!button.Enabled);
  }
}

// caller
ToggleButtons(new List<Button>() { button1, button2, button3 });

With a pre-requisite like this in place, it's then just a case of picking which buttons you want to enable/disable. A sensible choice might be to put all your related buttons in a container, so you can easily grab all the buttons from a given Panel or whatever.

As an aside, call your buttons something meaningful. button1 just won't do.

CodePudding user response:

Disable all buttons (but not disable any controls of other types) like this:

foreach (var button in Controls.OfType<Button>())
    button.Enabled = false;

You can further discriminate which controls to disable based on any criteria you wish. For example, perhaps by looking at its Name. Disable any Button with a "2" in its name somewhere like this:

foreach (var button in this.Controls.OfType<Button>().Where(btn => btn.Name.Contains("2")))
    button.Enabled = false;

CodePudding user response:

You can data bind the intended buttons e.g.

using System;
using System.Windows.Forms;

namespace Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();

            button2.DataBindings.Add("Enabled", button1, "Enabled");
            button3.DataBindings.Add("Enabled", button1, "Enabled");
        }

        private void ToggleEnableButton_Click(object sender, EventArgs e)
        {
            button1.Enabled = !button1.Enabled;
        }
    }
}

Or another option, if some of the buttons are on the form while others are in a panel or group box the following stores buttons in this case ending with a digit (or use other logic to determine which buttons in the list are to be targeted e.g. set the Tag property to a value and work off that value).

Keep in mind that the where condition here is based off your example but as mentioned above can be any logic you see fit.

Form code

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Demo
{
    public partial class Form1 : Form
    {
        private readonly List<Button> _buttonsList;
        public Form1()
        {
            InitializeComponent();

            _buttonsList = this.Buttons();

        }

        private void ToggleEnableButton_Click(object sender, EventArgs e)
        {
            _buttonsList.ToggleEnableState();
        }
    }
}

Helpers

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Demo
{
    static class  ControlExtensions
    {
        /// <summary>
        /// Get all buttons on a control/form or container
        /// </summary>
        /// <param name="control">form or container</param>
        /// <returns>list of buttons</returns>
        public static List<Button> ButtonList(this Control control) => 
            control.Descendants<Button>().ToList();

        /// <summary>
        /// Get all buttons in a list of buttons where the button name ends with a digit
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        public static List<Button> Buttons(this Control sender) => 
            sender.ButtonList().Where(button => 
                char.IsDigit(button.Name[button.Name.Length - 1])).ToList();


        /// <summary>
        /// Toggle the state of the buttons enabled property
        /// </summary>
        /// <param name="sender">form or container</param>
        public static void ToggleEnableState(this List<Button> sender)
        {
            foreach (var button in sender)
            {
                button.Enabled = !button.Enabled;
            }
        }

        /// <summary>
        /// Set enable property
        /// </summary>
        /// <param name="sender">form or container</param>
        /// <param name="enabled">true or false</param>
        public static void SetEnableState(this List<Button> sender, bool enabled)
        {
            foreach (var button in sender)
            {
                button.Enabled = enabled;
            }
        }
        public static IEnumerable<T> Descendants<T>(this Control control) where T : class
        {
            foreach (Control child in control.Controls)
            {
                T thisControl = child as T;
                if (thisControl != null)
                {
                    yield return (T)thisControl;
                }

                if (child.HasChildren)
                {
                    foreach (T descendant in Descendants<T>(child))
                    {
                        yield return descendant;
                    }
                }
            }
        }
    }
}
  •  Tags:  
  • c#
  • Related