NinethSense oWnZ mE!: Praveen’s drawing book

Choose a Topic:

Wed
8
Aug '07

Checkbox - Check All, None

This sample code demonstates the working of ‘check all’ and ‘check none’ checkbox behaviours in a Windows Forms application


 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void CheckCheck(object sender, EventArgs e) 
        {
            bool flag = true;
            foreach (Control ctrl in Form1.ActiveForm.Controls)
            {
                if (ctrl is CheckBox && ctrl.Name != “chkNone” && ctrl.Name != “chkAll”)
                {
                    CheckBox chk = (CheckBox)ctrl;
                    if (chk.Checked) flag = false;
                }
            }
            chkNone.Checked = flag;
        }
 
 
        private void chkNone_MouseClick(object sender, MouseEventArgs e)
        {
            CheckAll(false);
        }
 
        private void chkAll_MouseClick(object sender, MouseEventArgs e)
        {
            CheckAll(true);
        }
        private void CheckAll(bool b)
        {
            foreach (Control ctrl in Form1.ActiveForm.Controls)
            {
                if (ctrl is CheckBox && ctrl.Name != “chkNone” && ctrl.Name != “chkAll”)
                {
                    CheckBox chk = (CheckBox)ctrl;
                    chk.Checked = b;
                }
            }
        }
 
     }
}



Notes:

CheckCheck() method must be attached to CheckedChanged event of ALL the checkboxes except “None” and “All”.
chkNone_MouseClick() method is for the MouseClick event of “None” checkbox.
chkAll_MouseClick() method is for the MouseClick event of “All” checkbox.
The CodeProject Microsoft Developer Network Official ASP.NET Forums Microsoft .NET Framework Community Microsoft Most Valuable Professional Kidoos forums Microsoft Visual Studio Developer Home Professional Information Technology Solutions Microsoft Research Home Trivandrum Microsoft Users Group Community Website