Windows Forms 2.0 – CheckBox Control Recipes

Posted by: Suprotim Agarwal , on 9/3/2008, in Category WinForms & WinRT
Views: 50304
Abstract: In this article, we will explore how to perform some common tasks using the CheckBox Control of Windows Forms 2.0.
Windows Forms 2.0 – CheckBox Control Recipes
 
The System.Windows.Forms.CheckBox control lets the user pick a combination of options. It displays checkmarks that allow the user to toggle a condition. You can use check box controls in groups to display multiple choices from which the user can select one or more. The CheckBox control can display an image or text or both.
How Do I Get Started With The CheckBox Control
 
The System.Windows.Forms.CheckBox control lets the user pick a combination of options. It displays checkmarks that allow the user to toggle a condition. You can use check box controls in groups to display multiple choices from which the user can select one or more. The CheckBox control can display an image or text or both.
The following code example creates and initializes a CheckBox, adds an event handler to it, and then finally adds it to the Controls collection of the Form.
 
private void CreateCheckBox()
{
CheckBox cbOne = new CheckBox();
cbOne.Location = new Point(30,30);
cbOne.Text = "CheckBoxOne";
cbOne.CheckedChanged += new EventHandler(cbOne_CheckedChanged);
Controls.Add(cbOne);
}
 
private void cbOne_CheckedChanged(object sender, EventArgs e)
{
      // Place your code here.
}
 
Note : To Change the appearance of the CheckBox such as that of a toggle button, set cbOne.Appearance = Appearance.Button.
 
How Do I Determine the State of A CheckBox
 
The CheckBox control displays a check mark when it is selected. This can be determined programmatically at runtime by using the Checked property.
The ThreeState property determines whether the control supports two or three states. To get the value of a two-state CheckBox control , use the Checked property and to get the value of a three-state CheckBox control, use the CheckState property.
To run the the code sample, add a CheckBox (cbTwo) to the form. When the CheckBox control's CheckedChanged event is raised, a MessageBox pops up and determines the State of the checkbox by using the check box’s checked property.
// Determine current state
private void cbTwo_CheckedChanged(object sender, EventArgs e)
{
if (cbTwo.CheckState == CheckState.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("Unchecked");
}
}
 
How Do I Give The CheckBox Control A Transparent BackGround
 
By default, controls do not support transparent backcolors. A control can enable a style by using the Control.SetStyle Method in the constructor and passing in the appropriate ControlStyles bit (or bits) and the Boolean value to set the bit(s) to. This can allow your control to have a background color that is transparent, opaque or semitransparent. Another option to do the same, is by subclassing the CheckBox Control.
The following code sample subclasses the CheckBox control and sets the SupportsTransparentBackColorstyle bit to true.
 
// Subclassing the CheckBox control
public class MyCheckBox : CheckBox
{
public MyCheckBox(): base()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
}
 
 
// Create an object of the MyCheckBox Class in your code and use it.
 
MyCheckBox cb = new MyCheckBox();
cb.Location = new Point(30, 120);
cb.Text = "A Transparent One";
cb.BackColor = Color.Transparent;
 
// Even with themes enabled, this will display a white background
cb.FlatStyle = FlatStyle.System;
Controls.Add(cb);
 
Note : You can also create colors that are partially transparent using the Color.FromArgb method.
 
How Do I Count The Number Of CheckBoxes Checked On A Form
 
You have a bunch of dynamic checkboxes created on a form, and you need to count the total number of checkboxes checked.
The checked property gets or sets a value indicating whether the CheckBox is in the checked state. This property returns true if the CheckBox is in the checked state; else it returns false. The default value is false.
 
The following code example loops through the Controls collection in the form and checks if that control is a checkbox. It then uses the CheckState property to get the state of the CheckBox. If checked, it increases the iTot counter and on completion of the loop, finally returns the total. This example requires that a few CheckBoxes, and a Button (btnCntChk) have all been instantiated on a form.
 
private void btnCntChk_Click(object sender, EventArgs e)
{
MessageBox.Show(String.Format("No of Checked CheckBoxes are {0}", CountCheckBox(this).ToString()));
}
 
private int CountCheckBox(Control ctrl)
{
int iTot = 0;
foreach (Control c in ctrl.Controls)
{
if ((c is CheckBox && ((CheckBox)(c)).CheckState == CheckState.Checked))
{
iTot += 1;
}
else
{
iTot += CountCheckBox(c);
}
}
return iTot;
}
 
How Do I Check/Uncheck all CheckBoxes on a Form
 
private void btnUncheck_Click(object sender, EventArgs e)
{
CheckBox chkbox;
foreach (Control c in this.Controls)
{
if (c is CheckBox)
{
chkbox = (CheckBox)c;
chkbox.CheckState = CheckState.Unchecked;
// To Check All CheckBoxes, use CheckState.Checked
}
}
}
 
How Do I Create a ReadOnly CheckBox Without Disabling the Control
 
The CheckBox’s AutoText property gets or set a value indicating whether the Checked or CheckState values and the CheckBox’s appearance are automatically changed when the CheckBox is clicked. This property returns a true if the Checked value or CheckState value and the appearance of the control are automatically changed on the Click event; otherwise, false. The default value is true. By setting the AutoCheck property, you can manipulate the change state when clicked.
The following code example creates and initializes a CheckBox, adds an event handler and sets the AutoCheck property to false when the event is handled.
 
// Create a class level variable
// CheckBox cbRead;
 
private void CreateReadOnlyCheckBox()
{
cbRead = new CheckBox();
cbRead.CheckedChanged += new EventHandler(this.cbRead_CheckedChanged);
cbRead.Checked = true;
cbRead.Location = new Point(30,90);
cbRead.Text = "Read Only";
Controls.Add(cbRead);
}
 
private void cbRead_CheckedChanged(object sender, System.EventArgs e)
{
 
cbRead.AutoCheck = false;
 
}
 
Conclusion :
 
In this article, we saw a recipe approach to performing some of the most common tasks with the CheckBox Control. I hope the article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed. 
 
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook