Tom Pitts
Tom Pitts

Reputation: 600

Check more than one checkbox upon clicking a button c#

I have for example:

Checkbox1.IsChecked = true;
Checkbox2.IsChecked = true;
Checkbox3.IsChecked = true;

I have this 32 times. Is there a way to have concat string? For example:

i = 1
while i < 32:
    ("Checkbox"+ (i)).IsChecked = true;
    i++

Thanks

Upvotes: 0

Views: 664

Answers (2)

Alireza Noori
Alireza Noori

Reputation: 15253

There are multiple methods to achieve this.

  1. Add all of them to a generic List<> and iterate through them like the for you mentioned.
  2. Use reflection and get the checkbox controls and set their value.

Sample WinForms Code

    private List<CheckBox> checkboxes = new List<CheckBox>();

    public Form1()
    {
        InitializeComponent();
        FillCheckboxes();
    }

    private void CheckAll()
    {
        foreach (var chk in checkboxes)
        {
            chk.Checked = true;
        }            
    }

    private void FillCheckboxes()
    {
        foreach (Control c in this.Controls)
        {
            if (c is CheckBox)
            {
                checkboxes.Add(c as CheckBox);
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        CheckAll();
    }

Sample WPF Code

    private List<CheckBox> checkboxes = new List<CheckBox>();

    public Window1()
    {
        InitializeComponent();
        checkboxes = FindVisualChildren<CheckBox>(main).ToList();

        CheckAll();
    }

    private void CheckAll()
    {
        foreach (var chk in checkboxes)
        {
            chk.IsChecked = true;
        }
    }

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }

Important Note

For WPF the suggested method is to use data binding instead of iterating through controls and manually checking/unchecking them. Just bind the IsChecked property to the desired value and change it. You can find more info regarding this on numerous articles on the Internet.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

While you cannot do exactly what you intend, you can check or uncheck all checkboxes that are in a given container. For example, let's say you have a Panel that contains a number of checkboxes, called pnlChecks. You could do something like

foreach (var chkBox in pnlChecks.Controls.OfType<CheckBox>())
{
    chkBox.IsChecked = true;
}

Upvotes: 5

Related Questions