Button-Based Controls: Check Boxes |
|
Overview of Check Boxes
Introduction
A check box is a control that makes a statement true or false. To perform this validation, the control displays a small square box that the user can click. Here are examples:
To start, the square box may be empty . If the user clicks it, a check mark appears in the square box . If the user clicks a check box that has a check mark in it, the check mark may be removed.
To let the user know what the check box control represents, the control is accompanied by a label that displays the statement. When the square box is empty *, the statement is false. When the square box is filled with a check mark T, the statement is true.
Creating a Check Box
To support check boxes, the .NET Framework provides the CheckBox class. To add a check box to your application at design time, from the Common Controls section of the Toolbox, yon can click the CheckBox control and click the form or a container on the form. Unlike the radio button but like the regular command button, a check box can safely be positioned directly on a form.
To programmatically create a check box, declare a variable of type CheckBox, use the new operator to allocate memory for it, and add it to the Controls collection of its holder. Here is an example:
using System; using System.Drawing; using System.Windows.Forms; public class Exercise : System.Windows.Forms.Form { CheckBox chkValidate; public Exercise() { InitializeComponent(); } private void InitializeComponent() { chkValidate = new CheckBox(); Controls.Add(chkValidate); } } public class Program { static int Main() { System.Windows.Forms.Application.Run(new Exercise()); return 0; } }
Unlike the radio button that usually comes along with other radio buttons, a check box can appear by itself. Even when it comes in a group with others, the behavior of one check box is independent of the other check boxes, even if they belong to the same group.
Control | Text | Name | Additional Properties | |
GroupBox | Pizza Size | |||
RadioButton | Small | rdoSmall | ||
TextBox | 8.95 | txtSmall | AlignText: Right | |
RadioButton | Medium | rdoMedium | Checked: True | |
TextBox | 10.75 | txtMedium | AlignText: Right | |
RadioButton | Large | rdoLarge | ||
TextBox | 12.95 | txtLarge | AlignText: Right | |
GroupBox | Side Orders | |||
Label | Qty | |||
Label | Unit Price | |||
Label | Sub Total | |||
Label | Bread Sticks | |||
TextBox | 0 | txtQtyBread | AlignText: Right | |
TextBox | 3.25 | txtPriceBread | AlignText: Right | |
TextBox | 0.00 | txtTotalBread | AlignText: Right ReadOnly: True |
|
Label | Buffalo Wings | |||
TextBox | 0 | txtQtyWings | AlignText: Right | |
TextBox | 2.15 | txtPriceWings | AlignText: Right | |
TextBox | 0.00 | txtTotalWings | AlignText: Right ReadOnly: True |
|
GroupBox | Toppings | |||
CheckBox | Pepperoni | chkPepperoni | ||
CheckBox | Sausage | chkSausage | ||
CheckBox | Extra Cheese | chkExtraCheese | ||
CheckBox | Olives | chkOlives | ||
CheckBox | Onions | chkOnions | ||
Label | Each Topping | |||
TextBox | 0.45 | txtEachTopping | AlignText: Right | |
GroupBox | Drinks | |||
Label | Qty | |||
Label | Unit Price | |||
Label | Sub Total | |||
Label | Soda Can | |||
TextBox | 0 | txtQtyCan | AlignText: Right | |
TextBox | 1.45 | txtPriceCan | AlignText: Right | |
TextBox | 0.00 | txtTotalCan | AlignText: Right ReadOnly: True |
|
Label | Soda 20 Oz. | |||
TextBox | 0 | txtQtySoda20 | AlignText: Right | |
TextBox | 1.45 | txtPriceSoda20 | AlignText: Right | |
TextBox | 0.00 | txtTotalSoda20 | AlignText: Right ReadOnly: True |
|
Label | Soda 2L Bottle | |||
TextBox | 0 | txtQtySoda2L | AlignText: Right | |
TextBox | 1.45 | txtPriceSoda2L | AlignText: Right | |
TextBox | 0.00 | txtTotalSoda2L | AlignText: Right ReadOnly: True |
|
Label | Orange Juice | |||
TextBox | 0 | txtQtyOJ | AlignText: Right | |
TextBox | 2.25 | txtPriceOJ | AlignText: Right | |
TextBox | 0.00 | txtTotalOJ | AlignText: Right ReadOnly: True |
|
Label | Water | |||
TextBox | 0 | txtQtyWater | AlignText: Right | |
TextBox | 1.25 | txtPriceWater | AlignText: Right | |
TextBox | 0.00 | txtTotalWater | AlignText: Right ReadOnly: True |
|
Button | Close | btnClose | ||
Label | Total Price | |||
TextBox | 0.00 | txtTotalPrice | AlignRight: Right ReadOnly: True |
Check Box Characteristics
By default, a check box appears empty, which makes its statement false. To make the statement true, the user can click it. There are three main ways you can use this property of a check box. To select a check box, you can set its Checked property to True. You can also do it programmatically as follows:
private void Form1_Load(object sender, System.EventArgs e)
{
checkBox1.Checked = true;
}
To find out if an item is selected, get the value of its Checked property. Another possibility consists of toggling the state of the check mark. For example, you can check or uncheck the check mark when the user clicks another button. To do this, you can simply negate the truthfulness of the control as follows:
checkBox1.Checked = ! checkBox1.Checked;
Like the radio button, when a check box is clicked, the control fires a CheckedChanged event to let you know that it has been checked. This event is of type EventArgs. If the check box can display only two states, checked or unchecked, this event is enough.
Practical Learning: Configuring Check Boxes
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DaniloPizza1 { public partial class Exercise : Form { public Exercise() { InitializeComponent(); } internal void CalculatePrice() { double PriceSize = 0.00; double PriceEachTopping = 0.00, BWings, Bread, SodaCan, Soda20, Soda2L, OJ, Water, PriceToppings, TotalOrder; int Pepperoni, Sausage, ExtraCheese, Onions, Olives; try { // Get the price of pizza depending on the selected size if (rdoSmall.Checked == true) PriceSize = double.Parse(txtSmall.Text); if (rdoMedium.Checked == true) PriceSize = double.Parse(txtMedium.Text); if (rdoLarge.Checked == true) PriceSize = double.Parse(txtLarge.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the price of a pizza is invalid" + "\nPlease try again"); } // Get the price of a topping if it was selected if (chkPepperoni.Checked == true) Pepperoni = 1; else Pepperoni = 0; if (chkSausage.Checked == true) Sausage = 1; else Sausage = 0; if (chkExtraCheese.Checked == true) ExtraCheese = 1; else ExtraCheese = 0; if (chkOnions.Checked == true) Onions = 1; else Onions = 0; if (chkOlives.Checked == true) Olives = 1; else Olives = 0; // Get the price of each topping try { PriceEachTopping = double.Parse(txtEachTopping.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the price of a each topping is invalid" + "\nPlease try again"); } PriceToppings = (Pepperoni + Sausage + ExtraCheese + Onions + Olives) * PriceEachTopping; // Calculate the price of the side dishes // depending on the quantity entered BWings = double.Parse(txtTotalWings.Text); Bread = double.Parse(txtTotalBread.Text); // Calculate the price of the drink(s) SodaCan = double.Parse(txtTotalCan.Text); Soda20 = double.Parse(txtTotalSoda20.Text); Soda2L = double.Parse(txtTotalSoda2L.Text); OJ = double.Parse(txtTotalOJ.Text); Water = double.Parse(txtTotalWater.Text); TotalOrder = PriceSize + PriceToppings + BWings + Bread + SodaCan + Soda20 + Soda2L + OJ + Water; txtTotalOrder.Text = TotalOrder.ToString("F"); } private void rdoSmall_Click(object sender, EventArgs e) { CalculatePrice(); } private void txtSmall_Leave(object sender, EventArgs e) { int QtyBread = 0, QtyWings = 0, QtyCan = 0, QtySoda20 = 0, QtySoda2L = 0, QtyOJ = 0, QtyWater = 0; double PriceBread = 0.00, TotalBread = 0.00, PriceWings = 0.00, TotalWings = 0.00, PriceCan = 0.00, TotalCan = 0.00, PriceSoda20 = 0.00, TotalSoda20 = 0.00, PriceSoda2L = 0.00, TotalSoda2L = 0.00, PriceOJ = 0.00, TotalOJ = 0.00, PriceWater = 0.00, TotalWater = 0.00; // Retrieve the quantity set in the text box try { QtyBread = int.Parse(txtQtyBread.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of bread sticks is not valid" + "\nPlease try again!"); } // Get the unit price of the item try { PriceBread = double.Parse(txtPriceBread.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of bread sticks is not valid" + "\nPlease try again!"); } // Calculate the sub-total of this item TotalBread = QtyBread * PriceBread; // Display the sub-total in the corresponding text box txtTotalBread.Text = TotalBread.ToString("F"); try { PriceWings = int.Parse(txtQtyWings.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of orders of buffalo wings is not valid" + "\nPlease try again!"); } try { PriceWings = double.Parse(txtPriceWings.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of buffalo wings is not valid" + "\nPlease try again!"); } TotalWings = QtyWings * PriceWings; txtTotalWings.Text = TotalWings.ToString("F"); try { QtyCan = int.Parse(txtQtyCan.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of soda cans is not valid" + "\nPlease try again!"); } try { PriceCan = double.Parse(txtPriceCan.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of soda cans is not valid" + "\nPlease try again!"); } TotalCan = QtyCan * PriceCan; txtTotalCan.Text = TotalCan.ToString("F"); try { QtySoda20 = int.Parse(txtQtySoda20.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of soda 20 Oz. is not valid" + "\nPlease try again!"); } try { PriceSoda20 = double.Parse(txtPriceSoda20.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of soda 20 Oz. is not valid" + "\nPlease try again!"); } TotalSoda20 = QtySoda20 * PriceSoda20; txtTotalSoda20.Text = TotalSoda20.ToString("F"); try { QtySoda2L = int.Parse(txtQtySoda2L.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of bottles of soda 2-litter is not valid" + "\nPlease try again!"); } try { PriceSoda2L = double.Parse(txtPriceSoda2L.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of a bottle of soda is not valid" + "\nPlease try again!"); } TotalSoda2L = QtySoda2L * PriceSoda2L; txtTotalSoda2L.Text = TotalSoda2L.ToString("F"); try { QtyOJ = int.Parse(txtQtyOJ.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of a bottle of orange juice is not valid" + "\nPlease try again!"); } try { PriceOJ = double.Parse(txtPriceOJ.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of bottles of orange is not valid" + "\nPlease try again!"); } TotalOJ = QtyOJ * PriceOJ; txtTotalOJ.Text = TotalOJ.ToString("F"); try { QtyWater = int.Parse(txtQtyWater.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the quantify of bottles of water is not valid" + "\nPlease try again!"); } try { PriceWater = double.Parse(txtPriceWater.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the price of bottle of water is not valid" + "\nPlease try again!"); } TotalWater = QtyWater * PriceWater; txtTotalWater.Text = TotalWater.ToString("F"); CalculatePrice(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } } }
private void btnClose_Click(object sender, System.EventArgs e) { Close(); }
By default, the square box of a check control is positioned to the left side of its accompanying label. Instead of this default left position, you can change as you wish. The position of the round box with regards to its label is controlled by the CheckAlign property that of type ContentAlignment. To programmatically set the check alignment of a check box, you can call the ContentAlignment enumeration and select the desired value. Here is an example:
private void Form1_Load(object sender, System.EventArgs e)
{
this.checkBox1.Checked = true;
this.checkBox1.CheckAlign = ContentAlignment.MiddleRight;
}
The Checked State of a Check Box
Instead of being definitely checked, you can let the user know that the decision of making the statement true or false is not complete. This means that a check box can display as "half-checked". In this case the check mark would appear as if it were disabled. This behavior is controlled through the CheckState property. To provide this functionality, assign the Indeterminate value to its CheckState property. You can do this programmatically as follows:
this.ccheckBox1.CheckState = checkState.Indeterminate; |
The CheckState property only allows setting the check box control as "undecided". If you actually want the user to control three states of the control as checked, half-checked, or unchecked, use the ThreeState property.
By setting the CheckState Boolean property to true, the user can click it two to three times to get the desired value. When this ability is given to the user, you can use or check the value of the Indeterminate property to find out whether the control is checked, half-checked, or unchecked.
Here is an example of specifying the check box control as being able to display one of three states:
private void Form1_Load(object sender, System.EventArgs e)
{
checkBox1.Checked = true;
checkBox1.ThreeState = true;
}
If a check box is configured to assume one of three states when it's clicked, that is, if the ThreeState property of a check button is set to True, when the user clicks such a button, the button acquires one of the available three states, which are Checked, Unchecked, or Indeterminate. This causes the control to fire a CheckStateChanged event. This event also is of type EventArgs. This means that it does not let you know the current state of the button. You would have to find it out yourself, which is easily done by getting the value of the CheckState property.
By default, a check box appears as a square box that gets a check mark when the user clicks it. Optionally, you can make a check box appear as a toggle button. In that case, the button would appear as a regular button. When the user clicks it, it appears down. If the user clicks it again, it becomes up.
To change the appearance of a check box, assign the Button or Normal value to its Appearance property. The Appearance values are defined in the Appearance enumeration. You can also do this programmatically as follows:
private void Form1_Load(object sender, System.EventArgs e)
{
checkBox1.Checked = true;
checkBox1.ThreeState = true;
checkBox1.Appearance = Appearance.Button;
}
Like the radio button, the check box control fires an AppearanceChanged event when the button's appearance changes from Normal to Button or vice-versa.
Practical Learning: Using the Appearance of a Check Box
Control | Text | Name | Font | FlatStyle | Appearance |
Label | A | Microsoft Sans Serif, 24pt | |||
Label | B | Microsoft Sans Serif, 24pt | |||
Label | A ^ B | lblOperation | Microsoft Sans Serif, 24pt | ||
CheckBox | False | chkOperand1 | Microsoft Sans Serif, 18pt | System | Button |
CheckBox | False | chkOperand2 | Microsoft Sans Serif, 18pt | System | Button |
CheckBox | False | chkResult | Microsoft Sans Serif, 18pt | System | Button |
Button | New Operation | btnNewOperation | Microsoft Sans Serif, 15.75pt | ||
Button | Check | btnCheckOperation | Microsoft Sans Serif, 18pt | ||
Button | Close | btnClose | Microsoft Sans Serif, 15.75pt |
private void chkOperand1_CheckedChanged(object sender, EventArgs e) { if (chkOperand1.Checked == true) chkOperand1.Text = "True"; else chkOperand1.Text = "False"; }
private void chkOperand2_CheckedChanged(object sender, EventArgs e) { if (chkOperand2.Checked == true) chkOperand2.Text = "True"; else chkOperand2.Text = "False"; }
private void chkResult_CheckedChanged(object sender, EventArgs e) { if (chkResult.Checked == true) chkResult.Text = "True"; else chkResult.Text = "False"; }
private void btnNewOperation_Click(object sender, EventArgs e) { string[] strBooleanValues = { "True", "False" }; string[] strOperations = { "A ^ B", "A V B" }; Random rnd = new Random(); chkOperand1.Text = strBooleanValues[rnd.Next(2)]; chkOperand2.Text = strBooleanValues[rnd.Next(2)]; if (chkOperand1.Text == "True") chkOperand1.Checked = true; else chkOperand1.Checked = false; if (chkOperand2.Text == "True") chkOperand2.Checked = true; else chkOperand2.Checked = false; lblOperation.Text = strOperations[rnd.Next(2)];
private void btnCheckResult_Click(object sender, EventArgs e) { // Logical Conjunction if (lblOperation.Text == "A ^ B") { // If A = true if (chkOperand1.Checked == true) { if (chkOperand2.Checked == true) { if (chkResult.Checked == true) { // | A | B | A ^ B | // | T | T | T | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == false) { // | A | B | A ^ B | // | T | T | F | MessageBox.Show("Wrong - Get it right next time!"); } } else if (chkOperand2.Checked == false) { if (chkResult.Checked == false) { // | A | B | A ^ B | // | T | F | F | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == true) { // | A | B | A ^ B | // | T | F | T | MessageBox.Show("Wrong - Get it right next time!"); } } } else if( chkOperand1.Checked == false ) { if (chkOperand2.Checked == true) { if (chkResult.Checked == false) { // | A | B | A ^ B | // | F | T | F | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == true ) { // | A | B | A ^ B | // | F | T | T | MessageBox.Show("Wrong - Get it right next time!"); } } else if (chkOperand2.Checked == false) { if (chkResult.Checked == false) { // | A | B | A ^ B | // | F | F | F | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == true) { // | A | B | A ^ B | // | F | F | T | MessageBox.Show("Wrong - Get it right next time!"); } } } } else if (lblOperation.Text == "A V B") // Logical Disjunction: { // If A = true if (chkOperand1.Checked == true) { if (chkOperand2.Checked == true) { if (chkResult.Checked == true) { // | A | B | A V B | // | T | T | T | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == false) { // | A | B | A V B | // | T | T | F | MessageBox.Show("Wrong - Get it right next time!"); } } else if (chkOperand2.Checked == false) { if (chkResult.Checked == true) { // | A | B | A V B | // | T | F | T | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == false) { // | A | B | A V B | // | T | F | F | MessageBox.Show("Wrong - Get it right next time!"); } } } else if (chkOperand1.Checked == false) { if (chkOperand2.Checked == true) { if (chkResult.Checked == true) { // | A | B | A V B | // | F | T | T | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == false) { // | A | B | A V B | // | F | T | F | MessageBox.Show("Wrong - Get it right next time!"); } } else if (chkOperand2.Checked == false) { if (chkResult.Checked == false) { // | A | B | A V B | // | F | F | F | MessageBox.Show("Bravo - Good Answer"); } else if (chkResult.Checked == true) { // | A | B | A V B | // | F | F | T | MessageBox.Show("Wrong - Get it right next time!"); } } } } }
private void btnClose_Click(object sender, EventArgs e) { Close(); }
Check Boxes and Databases
Data Entry With Check Boxes
As you may know already, Boolean values are represented in Transact-SQL with the BIT data type, which is actually a small integer. On the other hand, the .NET Framework check box holds a property named Checked that can be TRUE or FALSE. Based on this, when a user has clicked a check box, you can specify the SQL's bit value as 1, otherwise it would be false. Here is an example:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsControls1 { public partial class Exercise : Form { public Exercise() { InitializeComponent(); } private void btnCreateDatabase_Click(object sender, EventArgs e) { string strConnection = "Data Source=(local);Integrated Security=yes"; using (SqlConnection connection = new SqlConnection(strConnection)) { SqlCommand command = new SqlCommand("CREATE DATABASE MotorVehicleAdministration1;", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A database named \"MotorVehicleAdministration\" has been created.", "Motor Vehicle Administration", MessageBoxButtons.OK, MessageBoxIcon.Information); } using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='MotorVehicleAdministration1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("CREATE TABLE Drivers" + "(" + " DriverNumber nvarchar(25), " + " FullName nvarchar(50)," + " OrganDonor bit" + ");", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A new table named \"Drivers\" has been created.", "Motor Vehicle Administration", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnSubmit_Click(object sender, EventArgs e) { byte isOrganDonor = 0; using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='MotorVehicleAdministration1';" + "Integrated Security=yes;")) { if (chkIsOrganDonor.Checked == true) isOrganDonor = 1; SqlCommand command = new SqlCommand("INSERT INTO Drivers " + "VALUES(N'" + txtDriverNumber.Text + "', N'" + txtFullName.Text + "', " + isOrganDonor + ");", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A new record has been created.", "Motor Vehicle Administration", MessageBoxButtons.OK, MessageBoxIcon.Information); txtDriverNumber.Text = ""; txtFullName.Text = ""; chkIsOrganDonor.Checked = false; } } private void btnClose_Click(object sender, EventArgs e) { Close(); } } }
Boolean Values
A Boolean column must have a value of true or false. In Transact-SQL, such a field uses the bit data type. In the .NET Framework, the value can be provided by a check box whose Checked property holds a Boolean value. The value must be passed with single-quotes. Here is an example:
using System; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; public class Exercise : System.Windows.Forms.Form { Label lblEmployeeName; TextBox txtEmployeeName; Label lblMaritalStatus; DomainUpDown dudMaritalStatus; CheckBox chkHasChildren; Button btnCreateDatabase; Button btnAddEmployee; public Exercise() { InitializeComponent(); } void InitializeComponent() { btnCreateDatabase = new Button(); btnCreateDatabase.Text = "Create Database"; btnCreateDatabase.Location = new Point(12, 12); btnCreateDatabase.Width = 120; btnCreateDatabase.Click += new EventHandler(btnCreateDatabaseClick); lblEmployeeName = new Label(); lblEmployeeName.AutoSize = true; lblEmployeeName.Text = "Employee Name:"; lblEmployeeName.Location = new Point(12, 44); txtEmployeeName = new TextBox(); txtEmployeeName.Location = new Point(110, 44); lblMaritalStatus = new Label(); lblMaritalStatus.AutoSize = true; lblMaritalStatus.Text = "Marital Status:"; lblMaritalStatus.Location = new Point(12, 66); dudMaritalStatus = new DomainUpDown(); dudMaritalStatus.Items.Add("Single"); dudMaritalStatus.Items.Add("Married"); dudMaritalStatus.Items.Add("Separated"); dudMaritalStatus.Items.Add("Divorced"); dudMaritalStatus.Items.Add("Widow"); dudMaritalStatus.Location = new Point(110, 66); chkHasChildren = new CheckBox(); chkHasChildren.Text = "Has Children?"; chkHasChildren.Location = new Point(12, 86); chkHasChildren.CheckAlign = ContentAlignment.MiddleRight; btnAddEmployee = new Button(); btnAddEmployee.Text = "Add Employee"; btnAddEmployee.Location = new Point(12, 110); btnAddEmployee.Width = btnCreateDatabase.Width; btnAddEmployee.Click += new EventHandler(btnAddEmployeeClick); Text = "Database Exercise"; Controls.Add(lblEmployeeName); Controls.Add(txtEmployeeName); Controls.Add(lblMaritalStatus); Controls.Add(dudMaritalStatus); Controls.Add(btnAddEmployee); Controls.Add(btnCreateDatabase); Controls.Add(chkHasChildren); StartPosition = FormStartPosition.CenterScreen; } void btnCreateDatabaseClick(object sender, EventArgs e) { using (SqlConnection cntExercise = new SqlConnection("Data Source='EXPRESSION';" + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("IF EXISTS (SELECT name " + "FROM sys.databases WHERE name = N'Exercise1' " + ") " + "DROP DATABASE Exercise1; " + "CREATE DATABASE Exercise1;", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } using (SqlConnection cntExercise = new SqlConnection("Data Source='EXPRESSION'; " + "Database='Exercise1'; " + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("CREATE SCHEMA Personnel;", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } using (SqlConnection cntExercise = new SqlConnection("Data Source='EXPRESSION';" + "Database='Exercise1'; " + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("CREATE TABLE Personnel.Employees" + "(" + " EmployeeName nvarchar(50)," + " MaritalStatus int," + " HasChildren bit" + ");", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } } private void btnAddEmployeeClick(object sender, EventArgs e) { using (SqlConnection cntExercise = new SqlConnection("Data Source='EXPRESSION';" + "Database='Exercise1';" + "Integrated Security=SSPI;")) { SqlCommand cmdExercise = new SqlCommand("INSERT INTO Personnel.Employees " + "VALUES('" + txtEmployeeName.Text + "', " + dudMaritalStatus.SelectedIndex + ", '" + chkHasChildren.Checked + "');", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } } } public class Program { [STAThread] static int Main() { System.Windows.Forms.Application.Run(new Exercise()); return 0; } }
Check Boxes and Data Selection
A check box is used to display a value that can be considered true or false. In Transact-SQL, when creating a column for such a value, you can use the bit data type. When specifying the value of that column, you can assign 1 for true and 0 for false. In the same way, when getting a value for the column, you can check whether it holds 1 or 0.
If you are using a data reader to get the value of a column that has Boolean values, parse that value before applying it to the check box. Here is an example:
using System; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; public class Exercise : System.Windows.Forms.Form { Label lblEmployeeName; CheckBox chkIsFullTime; Button btnBinder; Button btnCreateDatabase; public Exercise() { InitializeComponent(); } void InitializeComponent() { btnCreateDatabase = new Button(); btnCreateDatabase.Text = "Create Database"; btnCreateDatabase.Location = new Point(12, 12); btnCreateDatabase.Width = 120; btnCreateDatabase.Click += new EventHandler(btnCreateDatabaseClick); btnBinder = new Button(); btnBinder.Text = "Bind"; btnBinder.Location = new Point(140, 12); btnBinder.Click += new EventHandler(btnBinderClick); lblEmployeeName = new Label(); lblEmployeeName.AutoSize = true; lblEmployeeName.Text = "Customer Name"; lblEmployeeName.Location = new Point(12, 44); chkIsFullTime = new CheckBox(); chkIsFullTime.Text = "Full Time?"; chkIsFullTime.CheckAlign = ContentAlignment.MiddleRight; chkIsFullTime.Location = new Point(12, 70); Text = "Database Exercise"; Controls.Add(lblEmployeeName); Controls.Add(btnBinder); Controls.Add(btnCreateDatabase); Controls.Add(chkIsFullTime); StartPosition = FormStartPosition.CenterScreen; } void btnCreateDatabaseClick(object sender, EventArgs e) { using (SqlConnection cntExercise = new SqlConnection("Data Source=(local); " + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("IF EXISTS (SELECT name " + "FROM sys.databases WHERE name = N'Exercise1' " + ") " + "DROP DATABASE Exercise1; " + "CREATE DATABASE Exercise1;", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } using (SqlConnection cntExercise = new SqlConnection("Data Source=(local); Database='Exercise1'; " + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("CREATE SCHEMA Personnel;", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } using (SqlConnection cntExercise = new SqlConnection("Data Source=(local); Database='Exercise1'; " + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("CREATE TABLE Personnel.Employees(EmployeeNumber nvarchar(8), " + "FirstName nvarchar(24), LastName nvarchar(24), " + "EmployeeName AS LastName + N', ' + FirstName," + "Title nvarchar(50), IsFullTime bit);", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } using (SqlConnection cntExercise = new SqlConnection("Data Source=(local); Database='Exercise1'; " + "Integrated Security='SSPI';")) { SqlCommand cmdExercise = new SqlCommand("INSERT INTO Personnel.Employees(EmployeeNumber, " + "FirstName, LastName, Title, IsFullTime) " + "VALUES(N'927049', N'Aaron', N'Swanson', N'General Owner', 1)," + " (N'297113', N'Jane', N'Simms', 'Account Associate', 1)," + " (N'804070', N'Justine', N'Aronson', 'Accountant', 0)," + " (N'284825', N'Paul', N'DaCosta', 'Webmaster', 0)," + " (N'380408', N'Desmond', N'Perez', 'Account Associate', 1);", cntExercise); cntExercise.Open(); cmdExercise.ExecuteNonQuery(); } } private void btnBinderClick(object sender, EventArgs e) { using (SqlConnection cntExercise = new SqlConnection("Data Source=(local);" + "Database='Exercise1';" + "Integrated Security=SSPI;")) { SqlCommand cmdExercise = new SqlCommand("SELECT ALL * FROM Personnel.Employees;", cntExercise); cntExercise.Open(); SqlDataReader rdrEmployees = cmdExercise.ExecuteReader(); while(rdrEmployees.Read()) { lblEmployeeName.Text = rdrEmployees[3].ToString(); chkIsFullTime.Checked = bool.Parse(rdrEmployees[5].ToString()); } } } } public class Program { [STAThread] static int Main() { System.Windows.Forms.Application.Run(new Exercise()); return 0; } }
If you are using the Binding class, when applying to the check box, pass the first argument of the Binding constructor as Checked. Here is an example:
private void btnBinderClick(object sender, EventArgs e) { using (SqlConnection cntExercise = new SqlConnection("Data Source=(local);" + "Database='Exercise1';" + "Integrated Security=SSPI;")) { SqlCommand cmdExercise = new SqlCommand("SELECT ALL * FROM Personnel.Employees;", cntExercise); SqlDataAdapter sdaExercise = new SqlDataAdapter(cmdExercise); DataSet dsEmployees = new DataSet("EmployeesSet"); cntExercise.Open(); sdaExercise.Fill(dsEmployees); lblEmployeeName.DataBindings.Add(new Binding("Text", dsEmployees.Tables[0], "EmployeeName")); chkIsFullTime.DataBindings.Add(new Binding("Checked", dsEmployees.Tables[0], "IsFullTime")); } }