C# MonthCalendar Control
Hello Everyone! I'm back to give you daily dose of information that resonates with your needs and requirements. Today, I'm going to uncover the details on the introduction to
C# MonthCalendar Control. It is referred as a graphical interface that is widely used to modify and set date information based on your requirements. It is slightly different than DateTimePicker control in which you can select range of dates. DateTimePicker allows you to set both date and time, however, MonthCalendar control gives you a permission to select date only, but it gives you flexibility of selecting range of dates. Let's dive in and explore what this control does and what are its main applications.
C# MonthCalendar Control
- C# MonthCalendar Control is known as graphical interface that is used to modify and select range of date information for required application.
- In order to create C# MonthCalendar control, open the windows form application and go to Toolbar appearing on the left side.
- Find the MonthCalendar control, drag and drop it over the Form.
- You can play with it and move it around over the Form with the help of mouse.
- There is another way of creating the MonthCalendar control. Just double click on the MonthCalendar control, it will automatically place the MonthCalendar control on the Form.
MonthCalendar Control Properties
- In order to set the MonthCalendar control properties, just right click on the MonthCalendar control and go to properties.
- Properties window will appear on the right side of the windows form application.
- MonthCalendar control comes with different useful properties including, name, location, font, forecolor, back color, margin, MaximumDate, MaximumSize etc. Let’s discuss them one by one. Following window will appear as click on the properties.
Name
- Name property defines the specific name of the control that is used to access it in the code. In the figure above, MonthCalendar control name is monthCalendar1.
BackColor and ForeColor
- BackColor property is used to change the background color of the MonthCalendar control.
- ForeColor is used to display text within a month.
SelectionRange and SelectionStart
- SelectionRange is widely used property which defines the selected range of dates in the control.
- SelectionStart property specifies the start date of the selected range of dates.
FirstDayOfWeek and ShowTodayCircle
- FirstDayOfWeek property gives you an option to start week in the application with your preferred day. By default Sunday is selected as the start of the week and Saturday is considered as the last day of the week.
- ShowTodayCircle property is used to set the circle around current date. By default the value of this property is set as true. You can set it to false if you want to remove the circle around the current date.
ShowDate, MinDate and MaxDate
- ShowDate property displays the current date at the bottom of the calendar if its value is set as true. Setting the value to false will disappear the date at the bottom of the calendar.
- The maximum and minimum time period in the control is set by using two properties MaxDate and MinDate. MaxDate determines the maximum valid date for the control.
- MinDate determines the minimum valid date for the control.
- The Visual Basic version we are using shows MaxDate as 12/31/9998 and MinDate as 1/1/1753
CalendarDimensions and TodayDate
- CalendarDimensions determines the number of months in a single grid. Default dimension is set as (1,1) which will only display one month range in the grid.
- Maximum 12 month can be displayed in a single grid. And maximum dimension you can set is (4,3) which shows 12 months in four columns and three rows.
- Following figure shows two columns and two rows in the calendar grid because dimensions are set as (2,2)
- Following code can be used to set the number of months vertically and horizontally.
monthCalendar1.CalendarDimensions = new System.Drawing.Size (3,2);
- TodayDate is very useful property that determines the current date it captures from the system. Great thing is that you can select any date explicitly using TodayDate property and set it as current date.
ShowWeekNumbers
- ShowWeekNumbers property allows you to display week number on the calendar. By default this property value is set as false.
- Set this value as true if you want to display number of weeks in the current month of the calendar.
- In the following figure, 9,10,11,12,13,14 are the week numbers of the calendar year.
BoldedDates and Dock
- BoldedDates is an important property that is used to highlight some dates on the calendar.
- In order to create bold dates, right click on the calendar and go to properties.
- Find the BoldedDates property and click the ellipsis of its field.
- This will allow you to open DateTime Collection Editor from where you can bold the dates of your own choice.
- You can click add in order to create date member.
- As you click add, DateTime field would appear under which you can select any date value.
- Repeat the same process again if you want to bold more dates on the calendar. Following figure shows how you can bold some dates.
- In order to create bolded dates in the code, you must create DateTime object. Add following code if you want to create specific dates in bold numbers.
DateTime myVacation1 = new DateTime(2018, 3, 16);
DateTime myVacation2 = new DateTime(2018, 3, 17);
monthCalendar1.AddBoldedDate(myVacation1);
monthCalendar1.AddBoldedDate(myVacation2);
- Dock property determines the location on the calendar on the main Form. It comes with different values including top, bottom, right, left, fill and none.
Example 1
- Following example shows two month of the calendar year in the MonthCalendar Control.
- This example shows how you can bold some specific dates of your own choice and how you can make use of properties like MaxDate, MinDate, MaxSelectionCount, ShowToday, ShowTodayCircle etc.
- The DateSelected event is also used and its output is displayed on the form.
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 WindowsFormsApplication26
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime myVacation1 = new DateTime(2018, 3, 16);
DateTime myVacation2 = new DateTime(2018, 3, 17);
monthCalendar1.AddBoldedDate(myVacation1);
monthCalendar1.AddBoldedDate(myVacation2);
this.monthCalendar1.CalendarDimensions = new System.Drawing.Size(2, 1);
this.monthCalendar1.FirstDayOfWeek = System.Windows.Forms.Day.Tuesday;
this.monthCalendar1.MaxDate = new System.DateTime(2028, 12, 31, 0, 0, 0, 0);
this.monthCalendar1.MinDate = new System.DateTime(1990, 1, 1, 0, 0, 0, 0);
this.monthCalendar1.MaxSelectionCount = 20;
this.monthCalendar1.ShowToday = true;
this.monthCalendar1.ShowTodayCircle = true;
this.monthCalendar1.ShowWeekNumbers = true;
this.monthCalendar1.DateSelected += new System.Windows.Forms.DateRangeEventHandler(this.monthCalendar1_DateSelected);
}
private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
// Show the start and end dates in the text box.
this.txtLabel.Text = "Date Selected: Start = " +
e.Start.ToShortDateString() + " : End = " + e.End.ToShortDateString();
}
- And in Visual Studio Windows Form Application code will appear like below.
That's all for today. I hope you have enjoyed the article. However, if you need help, you can ask me in the comment section below. I'd love to help you in this regard according to best of my expertise. Stay Tuned!
C# LinkLabel Control
Hey Everyone! Hope you all are doing great and enjoying your lives. My job is to keep you updated with useful information that helps you excel in your relevant field. Today, I am going to give the details on the
C# Linklabel Control. This control allows you to display a hyperlink. It exhibits all the properties given by C# Label Control but it is explicitly used for displaying useful information on the hyperlink. I'll try to cover each and every aspect related to C# Linklabel Control so you don't need to go anywhere for finding the information regarding this control. Let's hop on the board and dive in the details of this control and explore its properties step by step.
C# LinkLabel Control
- C# Linklabel Control is used to display hyperlink to provide useful information.
- In order to create C# Linklabel control, open the windows form application and go to Toolbar appearing on the left side.
- Find the Linklabel control, drag and drop it over the Form.
- You can play with it and move it around over the Form with the help of mouse.
- There is another way of creating the Linklabel control. Just double click on the Linklabel control, it will automatically place the Linklabel control on the Form.
Linklabel Control Properties
- In order to set the Linklabel control properties, just right click on the Linklabel control and go to properties.
- Properties window will appear on the right side of the windows form application.
- Linklabel control comes with different useful properties including, name, autosize, text, size, font, fontcolor, back color etc. Let's discuss them one by one. Following window will appear as click on the properties.
Name and Text Properties
- Name property defines the specific name of the control that is used to access it in the code. In the figure above, Linklabel control name is linkLabel1.
- Similarly, text property is used to display the descriptive text on the link. You can go to properties and change the name manually or you can change it in a code as well.
- Following code can be used to change the text of the Linklabel Control.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
linkLabel1.Text = "this is label one";
}
BackColor, BorderStyle, ForeColor Properties
- BackColor property is used to change the background color of the linklable control.
- BorderStyle is used to give linklable control a specific border style around the link text. It comes with two border styles including FixedSingle, Fixed 3D.
- ForeColor is used to change the forecolor of the linklabel control.
Font, AutoSize and TextAlign Properties
- Font property shows the font style of the text that can be used in linklabel control. When you go to properties, and click on Font property, it shows different font styles, size and
- AutoSize property is used to change the size of the linklable control. By default the value of AutoSize property is true, when it is true, you can not change the size of the linklable. When it is set to false, you can change the size of linklabel.
- Similarly, TextAlign property is used to align the linklabel text in the linklable control. It comes with 9 different options to align the text at different place on the linklabel control.
Image and ImageAlign Properties
- Image property is used to set the background of the linklabel control as an image.
- Similarly, ImganAlign property is used to align the image on the background of the linklabel control.
Color Properties
- LinkColor property shows the color of the link in linklabel control.
- LinkVisited property comes with two states true and false. When it is false, color of the link won't be changed once the link is visited. When it is set true, the color of the link will change once the link is visited.
- VisitedLinkColor property shows the color of the visited link. By default purple color is set to the VisitedLinkColor property.
- ActiveLinkColor property represents the color when you put the cursor on the link and click. The color appears before you fully clicked the link is ActiveLinkColor.
Example 1
- We are going to build a program which will allow the linklabel to open some website.
- In order to do this, open the windows form application and drag and drop the linklabel from the Toolbar to Form.
- Double click on the linklabel, following figure will appear.
- Now add "using System.Diagnostics" in the code just like the shown in the figure below.
- Now add following code in your application. When you run the application, and click on the link, it will allow the link to open the google website.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("www.google.com");
}
That's all for today. Thanks for reading the article. We always love when you keep coming back for what we have to offer. If you have any question you can ask me in the comment section below. I'd love to help you according to best of my expertise. Stay Tuned!
C# ListView Control
Hi Guys! Hope you are doing great. Our mission is to give you valuable knowledge related to your field so you keep coming back for what we have to offer. Today, I am going to unlock the details on the
C# ListView Control. It displays useful information about list of items by using various views available in the control. You can also have a look at LinkLabel and DateTimePicker that I have discussed previously. I'll try to cover every aspect related to ListView Control so you get a clear idea about this control and you don't need to go anywhere else for finding the information regarding this control. Let's get started.
C# ListView Control
- C# ListView Control is used to display list of items by using various views available in the control.
- It is very useful in developing the applications where you want the data to be arranged in the form of list.
- Creating a ListView Control in Windows Form Application is very easy.
- Simply open the windows form application and drag the listview control from the ToolBar to Form.
- You can also create it by double clicking the listview control on the ToolBar, it will automatically place the listview control on the Form. Once you create the listview control it will look like the figure below.
- You can change its location with the help of mouse.
- Once you click on the little arrow available on the top right corner, it will appear like the figure below.
- Here you can see the ListView Tasks from where you can add items, columns, groups in the list and can change the view of the list that comes with different view options including largeicon, smallicon, list, title.
ListView Properties
- LlistView control comes with lots of different properties which you can modify manually.
- In order to open the properties window, right click on the listview control on the Form and go to properties windows.
- Once you open the properties windows, it will appear like the figure below which comes with different available properties.
Name
- Go to properties window and find property "Name" which specifies the unique name of the control which is used to access it in the the main code.
Location and Size Properties
- Location property represents the starting point of the listview control on the main Form. In other words, it represents the coordinates of the upper left corner of the control relative to the upper left corner of the container.
- Size property defines the size of listview control on the main Form. You can put the width and length on the size property or you can increase the size of the control by clicking the lower right corner of the control and expanding it towards right side.
ForeColor and BackColor Propeties
- ForeColor represents the forecolor of the listview control on the main Form.
- BackColor property represents the background color of the listview control.
- You can change both forecolor and backcolor manually by simply going to the properties window by right clicking on the listview control or you can change them by the help of code. Following lines can be used to change fore and back color in the code.
listView1.BackColor = Color.Brown;
listView1.ForeColor = Color.Blue;
View, GridLines, FullRowSelect Properties
- View property comes with 5 options to view the data on the list. FullRowSelect Property allows the cursor to select all add appearing in single row.
- Similarly, if you set GridProperty property as true, it will put the grid lines on the listview control. Following lines can be used to access these properties in the code.
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
Items and CheckBoxes Properties
- Items property is very useful in this control that allows you to add items one by one. You can add items manually through this control but better way is using proper code to add items in the listview control.
- You can use these lines to add items in the code
ListViewItem lv1 = new ListViewItem("Adnan Aqeel");
lv1.SubItems.Add("123 main street");
lv1.SubItems.Add("25");
listView1.Items.Add(lv1);
- First we create three columns naming name, address and age and set the view to details. Then we add above lines in the main code by double clicking the listview control.
- CheckBoxes property allows you to add checkbox in the listed item. By default checkboxes property is false, set this property as true in order to add checkboxes of items in the control.
LabelEdit and HoverSelection Properties
- LabelEdit is very handy as it allows you to change the text of the items available in the list.
- Set this property as true in order to change the text of the items manually.
- However, you can also change text of the items dynamically in the code.
- HoverSelection property is used to make the item selected when someone hover the mouse on it.
- Set this property true in order to make the item selected over hovering the mouse over it.
HotTracking and Alignment Properties
- HotTracking property allows you to underline the text of the item and make it prominent when someone hovers mouse over the item in the list. Set this property as true in order to make this property useful.
- Alignment property is very useful that allows you to align the items in the list properly. It comes with four options including default, left, top, SnapToGird.
Columns and Groups Properties
- Columns property is very important property of the control that allows you to add the columns in the list. This property becomes handy when you are using the Details view of the control.
- Groups property allows you to distinguish the classes of items distinctively.
How to Add Columns in the ListView Control
Example 1
- Let's create a code for which we add items on the list step by step by the add button, then we remove the selected data from the delete button and then clear all data from the clear button in the windows form application.
- When we add one panel, three buttons, three textboxes, three labels and one listview on the main form, it will look like a figure below.
- Following is the code to run this application to add items in the list step by step and remove it or clear it completely.
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 WindowsFormsApplication20
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnAddRecord_Click(object sender, EventArgs e)
{
ListViewItem lv1 = new ListViewItem(txtStudentName.Text);
lv1.SubItems.Add(txtFatherName.Text);
lv1.SubItems.Add(txtRegistrationNo.Text);
lvRecord.Items.Add(lv1);
}
private void btnDeleteSelected_Click(object sender, EventArgs e)
{
lvRecord.Items.Remove(lvRecord.SelectedItems[0]);
}
private void btnClearAll_Click(object sender, EventArgs e)
{
lvRecord.Items.Clear();
}
}
}
- Following figure shows the code in Visual Studio.
- Here's a short video in which I have shown How to use C# ListView Control:
That's all for today. I hope you have enjoyed the article and got to know the features of listview control. We always love when you visit our website to resolve your issues related to engineering. However, if still you feel any doubt or have any question you can ask me in the comment section below. I'd love to help you according to best of my expertise. Stay Tuned!
C# DateTimePicker Control
Hi Guys! We always aspire to make yourself equipped with useful information so you can excel and grow in your relevant field. Today, I am going to uncover the details on
C# DateTimePicker Control. It allows you to select date and time and show it in specific format. It is extremely useful when you develop any application where you want date of birth of user in a specified format or where you want to display date and time explicitly. I'll try to discuss each and every feature of
C# DateTimePicker Control, so you don't have to go anywhere else for finding the information regarding this specific control. Let's get started.
C# DateTimePicker Control
- C# DateTimePicker Control allows you to select date and time and show in specified format.
- It is very useful in developing the applications where you want user data in the form of date of birth.
- It behaves like an interface where user can change the date and time information.
- The display of this control contains fields that are defined by the format string of the control.
- Creating a DateTimePicker control is very easy. Open your windows form application and drag and drop the DateTimePicker control from Toolbar that is appeared on the left side to your Form1.
- Or simply double click the DateTimePicker control, it will automatically be placed on your Form1 displayed on the screen.
- You can play with it and change its location in the given space of Form1 or resize it with the help of mouse.
- When you run the application, monthly calendar will be displayed on the screen, where you can see date, month year and day.
- You can select any date of your own choice. It will appear like the figure below.
- You can also change the format of the DateTimePicker control in the code. As you double click the Form1, following figure will appear.
- Simply put the following code under the Form1_Load function if you want to appear the date in this format i.e year/month/date.
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy/MM/dd";
}
Similarly, if you want the date to be appeared in this format i.e date/month/year. You can use the following code.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd/MM/yyyy";
- You can make your own custom time format by doing minor changing in code.
- Similarly, if you want the format where you want to show both date and time, you can use the following code.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy/MM/dd hh:mm:ss";
DateTimePicker Properties
- Setting the properties of DateTimePicker control is very easy. In order to open the properties of the DateTimePicker control just right click on the DateTimePicker control and select properties.
- Properties window will appear on the right side of the screen and it will appear like the figure below.
Name
- Name property defines the specific name of the DateTimePicker control which is user to access the control in the main code.
- In the figure above name of the DateTimePicker control is set as dateTimePicker1.
Location and Size Properties
- Location property defines the location of the DateTimePicker control with respect to x axis and y axis on the Form1.
- You can set values of your own choice by simply putting the values in the Location property box or you can move around the DateTimePicker control on the Form with the help of mouse.
- Size property defines the size of the DateTimePicker control. You can simply put the values of your own choice in the size property box or you can increase the size with the mouse by simply putting the cursor of the mouse of the right border of the control and expanding it towards right side or lower side.
Font and Format Properties
- Font property defines the text style of the DateTimePicker control.
- Go to the properties window and select the Font property.
- It will show font size with different font style. You can choose any style of your own choice.
- Similarly you can change the format of the DateTimePicker control. This control comes with four format including long, short, time and custom.
ShowChekBox and ShowUpDown Properties
- ShowCheckBox property allows the the control to be editable without using the calendar.
- This can be achieved by setting the ShowCheckBox as true.
- ShowUpDown property in the property window allows you to change the date and time by showing up and down value where you can increase and decrease the value of date and time.
- Set the ShowUpDown as true and modify the date and time of your own choice.
- When you set both ShowCheckBox and ShowUpDown as true and run the application, following figure will appear.
Value
- Value property of DateTimePicker control is widely used in C#.
- It stores the current value of date and current in the control.
Example 1
Now we build a code where it will show the date and time in the specific format and when button is clicked, then code will show the current date and time stored in the DateTimePicker control. Check following code to understand this process.
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 WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy/MM/dd hh:mm:ss";
}
private void button1_Click(object sender, EventArgs e)
{
DateTime iDate;
iDate = dateTimePicker1.Value;
MessageBox.Show("Current date is " + iDate);
}
}
}
- When you run the application, and click the button, output will show in the following form.
How to Show Null Value in DateTimePicker Control
- It is important to note that we can not use null value in DateTimePicker control by default because it is a value type like int, bool, and float and it returns some value.
- You can make DateTimePicker control empty or it will show null value.
- First drag and drop one DateTimePicker control on the Form. Then right click on the DateTimePicker control and go to properties. Properties will appear on the right side of the screen.
- In the property window find the property "Format" and set it as Custom. Then find the property "CustomFormat" and simply add a space in the box. After you run the application it will show the empty box of DateTimePicker control.
- Or you can show DateTimePicker control empty by the following code.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
if (dateTimePicker1.Checked == false)
{
dateTimePicker1.CustomFormat = " ";
}
else
{
dateTimePicker1.CustomFormat = "yyyy/MM/dd hh:mm:ss";
}
- Before applying this code first we set ShowCheckBox as true in the property window of the DateTimePicker control. Then we apply this code.
- We are playing a trick here, we first set the format of the DateTimePicker as custom, then set the format text of the DateTimePicker as black space.
- This will do the trick and will set the DateTimePicker as blank when the box will be unchecked otherwise it will return some value.
- When you run this code output will appear like the figure below when ShowCheckBox is unchecked.
That's all for today. I have tried my best to give you valuable information in simple steps so you can get an easy grip on C# sharp language. However, if still you feel skeptical or have any doubt you can ask me in the comment section below. I'll go extra mile to help you solve your questions and queries as soon as possible. Stay Tuned!
C# CheckBox Control
Hi Guys! I hope you are doing great and having fun with your lives. Today, I am going to unlock the details on the
C# CheckBox Control. A CheckBox control is used to select the single or multiple options from the given list of options. I'll give you a brief detail how you can create CheckBox in the Windows form application. Also, I will discuss the properties and methods used in CheckBox control. You can also have a look at
C# Button Control. which we discussed in previous article. Let's hop on the board and dive in the details of CheckBox control.
C# CheckBox Control
- C# CheckBox Control is used to select the single or multiple options from the given list of options.
- In order to create CheckBox in design time, drag the CheckBox from the ToolBox located at the left side and drop it to the form1 main screen.
- As you create the CheckBox, it will look like the figure below.
- You can also create CheckBox in design time by simply double clicking on the CheckBox control.
- As you double click on the CheckBox control, it will create a CheckBox on the form1.
CheckBox Properties
- As you drag and drop the CheckBox on Form1, next step is to check the properties of the CheckBox.
- You can check the properties of the CheckBox by right clicking on the CheckBox then go to properties option.
- Properties Window will look like below figure.
Location and Size Properties
- Location property defines the starting point of check box with respect to x axis and y axis on the form1.
- You can simply click on the CheckBox and change the location of the box.
- Similarly, size property defines the size of the CheckBox control.
BackColor, BackgroundImage, ForeColor Properties
- BackColor is used to define the background color of the CheckBox.
- You can simply go to BackColor property in the property menu of the CheckBox and choose the color of your own choice.
- BackgroundImage is used to select the background image of the CheckBox.
- Go to the BackgroundImage property and choose the image of your own choice.
- ForeColor defines the foreground color of the checkbox.
- In the first figure forecolor of the checkBox1 is black.
- You can go to the ForeColor property of the properties list and choose the color of your own choice.
Name, Font, Appearance Properties
- Name defines the unique name of the CheckBox control which is used to access the CheckBox control in the main code.
- In the first figure, name of the CheckBox is checkBox1.
- Font property is used to select the font of the text the appears on the CheckBox control. As you click on the Font property, you can choose the desired font from the available list of font styles.
- From appearance property, you can select between two appearance options i.e. normal or button. Normal checkbox will look like as shown in the first figure. While button option will appear like the figure below.
Text, TextAlign and CheckAlign Properties
- Text property of the CheckBox is used to change the text that appears on the CheckBox.
- In the first figure, text that appears on the CheckBox is checkBox1.
- The TextAlign property defines the text alignment of the text that can be from TopLeft to BottomRight.
- CheckAlign property represents the alignment of the check mark in the CheckBox control.
- In the first figure the alignment of the check mark is MiddleLeft.
CheckState and Checked Properties
- CheckState define the state of the checkbox which can be checked, unchecked and intermediate.
- CheckBox control will be checked if check mark on the CheckBox control is checked and it will be unchecked if the check mark of the CheckBox control is unchecked.
- CheckState is directly connected with the Checked property of the CheckBox control.
- If CheckState is Checked or Intermediate then Checked property will be true and if CheckState is Unchecked then Checked property will be false.
Example 1
- This example will clearly elaborate the use of check box.
- Simply open the windows form application in C#.
- Then drag and drop a button and four check boxes from the Toolbar to Form1.
- Change the name of each check box by right clicking on each checkbox separately and then go to the properties of the checkbox and find "text" property. And change the name of the button to "Combine" by similar process.
- In next step, change the Checked property of both L and T checkboxes and set it to true.
- As you set the Checked property to true it will automatically change the CheckState and set it to as Checked.
- Now double click on the combine button it will take you to the window like below.
- In the figure above button1_Click function which will be get called when the button will be clicked in Windows form application.
- Now copy and paste the code below in your button function.
private void button1_Click(object sender, EventArgs e)
{
String last = "this is check box ";
if (checkBox1.CheckState == CheckState.Checked)
{
last += "L";
}
if (checkBox2.CheckState == CheckState.Checked)
{
last += "A";
}
if (checkBox3.CheckState == CheckState.Checked)
{
last += "S";
}
if (checkBox4.CheckState == CheckState.Checked)
{
last += "T";
}
MessageBox.Show(last);
}
- There are four condition of this code.
- If first condition will be true i.e. CheckState of the checkBox1 is checked and it will go to next step and call the word last with addition of "L" which is a string and is equal to "this is a check box".
- So when first condition will be true, output of the code will be shown like below.
When all four CheckBoxes are checked then it will show an output like below.
That's all for today. I hope you have got a clear idea about checkbox. However, if still you feel skeptical or have any doubt, you can ask me in the comment section below. I'll help you according to best of my expertise. Your suggestions and feedback will be highly appreciated. We always love when we are able to meet your needs and expectations. Stay tuned!
Introduction to C# Classes
Hi Everyone! Hope you all are doing great. We always love when you keep coming back for what we have to offer. Today, I am going to give you a
Introduction to C# Classes. We have already seen Introduction to Data Types in C# which includes boolean, integer, char and double. However, if you want to make complex custom type, you can make use of classes. I'll give you a brief introduction to classes so you don't have to go anywhere to find information regarding classes in C#. Let's hop on the board and dive in the details of classes.
Introduction to C# Classes
- Class in C# is referred as a blueprint of complex data type that describes the behavior and data of type.
- If you want to create complex custom type, we use class. What do I mean by complex custom type?
- Suppose you want to store a number 123, you can store it easily in an integer variable.
- However, if you want to store the customer's information, you can use classes like what kind of information customer has, what is his first and last name, his email ID, phone number and age etc.
- By using a built-in fields we can create a class.
- Fields of class define the class data and methods define the behavior of the class.
- When we create customer class, it not only contains the data, it can also do certain things like save the customer to the data base, print the customer full name etc.
- So, class has state and behavior, state is nothing but data and behavior is nothing but what the class is capable of doing.
How to Create a Class
In order to create a class we use a class keyword followed by the name of the class and members of class are enclosed by curly brackets. Let's look at an example which will make things clear.
Example 1
Following figure shows the complete explanation of classes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Customer
{
string _firstName;
string _lastName;
public Customer (string FirstName, string LastName)
{
this._firstName = FirstName;
this._lastName = LastName;
}
public void PrintFullName()
{
Console.WriteLine("Full Name = {0}", this._firstName +" "+ this._lastName);
}
~Customer()
{
//clean up code
}
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Customer C1 = new Customer("Adnan", "Network");
C1.PrintFullName();
}
}
}
- In the above example first name and last name of the customer is stored in a string which represents the state of the class.
- To initialize these fields a class can also have an constructor.
- A constructor will have a same name as that of your class.
- We make constructor public which is an access modifier.
- Constructors are basically used to initialize the class fields.
- Then we pass two parameters into this constructor which are string FirstName and string LastName.
- Constructor doesn't return a value but it can take parameters.
- Then we use constructor to initialize these class fields i.e _firstname and _lastname.
- This field _firstname is equal to the parameter FirstName and the field _lastname is equal to the parameter LastName.
- Then we put "this" keyword before firstName and lastName which is used to define the instance of classes also referred as objects.
- So, basically we are using constructor to initialize the class fields with parameters that are passing into the constructor.
- In the next step we add a behavior which allows the class to do something.
- We want to print the full name of the customer. This is called the method of the class which tells the behavior of the class.
- So far, we have created constructor, two fields and a methods for the class.
- In the next step we call the destructor of the class.
- Destructor will have the same name as that of the class but it doesn't take parameters and doesn't have a return type.
- Usually in C# we don't require destructors.
- We use destructors to clean up the resources your class was holding on to during its life time.
- We don't need to call the destructors, they are automatically called by the garbage collector.
- In the next step we make use of class in our main method.
- In this step we create instance C1 of class Customer with using the keyword "new".
- This instance is also called the object of the class. Instances and Objects are used interchangeably.
- Then we call FirstName and LastName of the customer. When we put FirstName as Adnan, it will pass through the parameter (string FirstName) of the constructor. And put second name as Network that will pass through the parameter(string LastName) of the constructor.
- Constructors are called automatically when you create instance of class.
- Also, constructors are not mandatory to use, if you don't provide a constructor, .NET framework will automatically provide a default parameter less constructor.
- In the next step we print the full name of the customer.
Output
Output of the above program will be like below.
That's all for today. I hope you have got a clear idea about class, constructor and destructor used in C#. However, if still you feel any doubt or have any question you can ask me in the question below. I'll be happy to help you in this regard according to best of my expertise. Stay tuned!
Introduction to Data types in C#
Hey Guys! I hope you all are doing great. Today, I am going to give a detailed
Introduction to Data types in C#. It's our 3rd tutorial in C# series & it's a theoretical tutorial so you just need to read it once.
I'll try to cover every aspect related to Data types in C# so you get a clear picture of what are data types and why we need them? So, let's get started with Introduction to Data types in C#:
Introduction to Data types in C#
- Data Types in C# are used to inform the compiler about the type, size & nature of data that can be stored in a variable.
- Whenever we need to declare a variable, we need to inform the compiler about the data size & type of the variable.
- There are 3 types of data types available in C# programming, which are:
-
- Value Data Type
- Pointer Data Type
- Reference Data Type
- Here's a Flow Diagram of C# Data types for better understanding.
- Let's discuss these C# data types one by one in detail:
1. Value Data Types
- Value Data Type Variable is the simplest variable in C#, to which we can assign a value directly and they save this value on the stack, so it's not cleared by Garbage Collector.
- Each variable stores its data in a separate memory so we can't assign a single memory to multiple variables, although we can update their data quite easily.
- Value data types are further divided into two types, named:
- Predefined data types.
- User defined data types.
A. Predefined Value Data Types: These Value Data Types are predefined in C# i.e. bool, int, float, decimal, char etc.
- Bool: a short form of Boolean, contains two values i.e. true or false.
- Int: a short form of integer.
- Char: a short form of character, which is used to store alphabets.
- Float: is used to store a floating point number i.e. number with decimal values.
- Here's a table showing Memory Size & Range of these Data Types in C#:
B. User Defined Value Data Types: User can also create customized data types in C# using existing data types. i.e. structure or enumerations etc.
- Enumerations This value data type contains set of related named constants which are called as enumerator list. The "enum" is used to declare the word enumerations.
- Structure or struct is referred as a grouped list of variables that can be placed under one name in memory. It is same like a "Class" in the reference type.
Don't worry about these concepts, we will cover them on by one in our coming lectures.
2. Pointer Data Type
- The pointer, also called as indicator or locator, is a data type in C# that points towards the memory address of a data, we need to use ( * ) in its declaration.
- The pointer in C# can only hold the memory address of arrays and value types i.e. int, char, float etc.
- No conversion is allowed between pointer types and objects.
- However, conversion between two different pointer types is allowed, you can also convert between pointers and integral types.
- You can also point multiple pointers in same data type.
3. Reference Data Types
- Reference data types in C# don't consist of actual data, instead they point towards the reference to the data stored in a variable, it saves data in the heap.
- In reference data types, it's possible for two variable to reference to the same object.
- Reference Data Types are further divided into two types:
A. Predefined Reference Data Types: contain objects, strings etc.
- String is a sequence of finite characters which can contain spaces and number. Total number of characters in the string refers to the string length. i.e. "I need 20 dollars" is a string.
- Object is referred as a block of memory that executes according to the blueprint.
B. User Defined Reference Data Types: contain classes, interface, etc.
Nullable Data Types
- In C# data types, the most commonly used data types are Value Types & Reference Types. Pointer types are not used that much.
- In above discussion, we have seen that:
- Value Data Types: int, float, double, structs, enums etc.
- Reference Data Types: string, interface, class, delegates etc.
- By default, Reference data types are nullable datatypes i.e. we can assign null value to these datatypes.
- Let's say, if I want to initialize a string with null value, I need to use this code: string[ ] data = null;
- On the contrary, Value Data Types are non nullable by default in C# i.e. we can't initialize an integer with null value.
- But we can make a value data type nullable by using a ( ? ) sign in front of the datatype.
- int? i = null; It will work fine and won't create any error because now i has created a nullable integer.
Why we need nullable ?
- Let's say you are designing a sign up form and you want user to select the gender i.e. male or female.
- We can store this value in Boolean variable but what happens if the user doesn't select any value.
- That's where nullable comes in handy and in this third case where user hasn't selected any value, we can assign a null value to our Boolean variable.
That's all for today. I hope you have got a clear idea about data types in C# language. However, if still you feel skeptical or have any question, you can ask me in the comment section below. I'll try to resolve your query according to best of my expertise. Keep your feedback and suggestions coming, it will help us to augment the quality of our article and give you flawless work that resonates with your needs and expectations. Stay tuned!
C# PictureBox Control
Hey everyone hopes you are good. In this tutorial, I'm going to share an amazing GUI tool which is mostly used in Point of Sale application which is C# PictureBox Control. As the name reflects it's feature, it's the box which allows you to preview the images. In short, we can say that this the PictureBox which is used to show images on the application, such as the logo or social media icon etc. In my previous tutorials, I have explained
C# ListBox Control,
C# Button Control,
C# Label Control and
C# TextBox Control which are similar to C# PictureBox. You will get to know about each and everything of C# PictureBox including Events. You can simply drag and drop the C# PictureBox from the toolbox in design tab and adjust that according to your needs.
You can use C# PictureBox for many purposes according to your requirement of application development. In point of sale application developer used C# PictureBox to preview the image of a scanned item in the POS. If you are looking to add images in your desktop application then you have to use the C# PictureBox.
C# PictureBox Control
It's simple image box which allows you to add images in your desktop application. You can simply add PictureBox by drag the PictureBox object from the toolbox of design tab. PictureBox can't be received the inputs because it's not the selectable control tool like
C# ListBox Control,
C# Button Control,
C# Label Control and
C# TextBox Control etc. You can only add the images and perform any specific action with there event handlers.
Suppose that you are wanted to add the PictureBox in your application, then simply drag and drop. Then in the main code call by the object name which is by default pictureBox1. To show the image within PictureBox we have used the image property which will set the path of the image to be previewed in C# PictureBox. In the following code, you can be observed how we have set the path of the image for PictureBox.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile("c:\\testImage.jpg");
}
}
}
First, you have to declare the PictureBox image property then you have to define the path from the constructor of Image.FromFile as mention in above code. In the following image, you can preview that how we have set the TestImage inside PictureBox.
By default name of C# PictureBox is pictureBox1, if you are wanted to change the default name then you have to go to properties and search for the name. In the name, you can override the name easily. In the following image, you can see that how we have changed the name of C# PictureBox instance.
It will be helpful if you are working on the mega projects, to get remember which object is used for which specific purposes.
C# PictureBox Events
C# PictureBox Events will allow you to perform the specific task or functionality according to the requirements on specific actions done by the end-user. There are many Events which you can use with the PictureBox to make your desktop application more interactive. Here is the list of those events which we will discuss further in this tutorial.
- C# PictureBox Click Events
- C# PictureBox DoubleClick Events
- C# PictureBox MouseEnter Events
- C# PictureBox MouseHover Events
- C# PictureBox MouseLeave Events
There are many other events handler which you can be used, we have selected these events because these are frequently used during the development of desktop applications.
C# PictureBox Click Events
Click event is used to handle the click of the user on the PictureBox. Supposed you are wanted to perform any specific functionality when user will click on the PictureBox then you have to use the Click Event handler of PictureBox. You just need to declare the functionality within the click event. Whenever the user will click the picture box, click event capture the click and get executed. In the following code, you can observe that we have used simple message box within the Click event handler. So that when user will click on the PictureBox it will show the message prompt.
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;
namespace TEPArticle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TEPpictureBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("You Just Click On the TEP PictureBox");
}
}
}
You can declare any kind of functionality within the click event handler according to your desire, we just used the message box to minimize the code and save our time. The main purpose is to share the basic logic of click event handler. In the following image, you can observe that when we have to click the PictureBox it's prompt the message.
C# PictureBox DoubleClick Events
This event occurs when user will click twice on the PictureBox. Sometimes we have required performing any functionality when user will DoubleClick on the PictureBox. You just have to activate the DoubleClick event handler and declare the functionality which you want to perform. So that when user will click twice on the picture box that functionality get executed. In the following code, you can observe that how we have declared the message box in the double click event handler. When user will click twice on the picture box a prompt message appears.
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;
namespace TEPArticle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TEPpictureBox1_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show("You Just DoubleClick On the TEP PictureBox");
}
}
}
We have declared the message box in DoubleClick event handler. You can declare any other functionality within double click event handler. In the following image, you can be observed that how message prompt when user will click twice on the C# PictureBox.
C# PictureBox MouseEnter Events
This event handler is used to perform any action when the mouse cursor enters the boundaries of C# PictureBox. Supposed you are required to perform any functionality when even user will enter the mouse cursor in the boundaries of PictureBox. For this case, we will use the MouseEnter Event handler. We will declare a message box within the MouseEnter Event handler. Whenever you will enter the mouse to the visible part of PictureBox it will prompt the message box. In the following code, you can observe the whole scenario.
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;
namespace TEPArticle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TEPpictureBox1_MouseEnter(object sender, EventArgs e)
{
MessageBox.Show("You Just Enter in visible part of TEP PictureBox");
}
}
}
We have declared the message box within the MouseEnter event handler. Now when user will enter the mouse cursor to visible part message prompt. In the following image, you can observe the output of the above code.
C# PictureBox MouseHover Events
This event handler will occur whenever user will hover the mouse cursor for a while on PictureBox. There is a very little difference between MouseEnter and MouseHover Event handler. Until user will hover the mouse cursor this event will not be executed. Supposed that you are required to change the image of picture box whenever user will hover the mouse. For this scenario, we have created the code which you can get from the following.
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;
namespace TEPArticle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TEPpictureBox1_MouseHover(object sender, EventArgs e)
{
TEPpictureBox1.Image = Image.FromFile("C: \\Users\\Public\\Pictures\\test.jpg");
}
}
}
In the above code, you can observe that we have used the test.jpg as the image when the MouseHover event will be executed. You can declare any kind of functionality as you are required. You can replace the path of the image and set MouseHover event to your C# PictureBox. When you will execute the code and hover the mouse cursor on the PictureBox it will change the image.
C# PictureBox MouseLeave Events
This event is executed whenever the mouse cursor leaves the boundaries of PictureBox or the visible area. If you are wanted to perform any action when user will leave the PictureBox then you can use the MouseLeave event handler with C# PictureBox. In the following code, we have used MouseHover Event handler too along with the MouseLeave Event handler. We have declared pic1 for MouseHover and pic2 for MouseLeave event. When user will hover the mouse PictureBox set to pic1 and when leaving the PictureBox it will set to pic2. You can get the code from the following.
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;
namespace TEPArticle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TEPpictureBox1_MouseHover(object sender, EventArgs e)
{
TEPpictureBox1.Image = Image.FromFile("C: \\Users\\Public\\Pictures\\pic1.jpg");
}
private void TEPpictureBox1_MouseLeave(object sender, EventArgs e)
{
TEPpictureBox1.Image = Image.FromFile("C: \\Users\\Public\\Pictures\\pic2.jpg");
}
}
}
When you will execute above code, and hover the PictureBox the image get changed and when left the PictureBox image get change again. By this, you can create animated effects in your desktop application. Remember if you will copy the above code you have to add these event handlers to the C# PictureBox.
We have tried to give you basic to advance information about C# PictureBox. In this tutorials, you have learned many different techniques which are used in the professional development of desktop application along with the usage of Event handlers. After this, you can go for
C# ListBox Control,
C# Button Control,
C# Label Control and
C# ComboBox Control. In all of this, don't forget to subscribe our YouTube Channel
"TheEngineeringProjects" and
C# Video Tutorial PlayList.
C# Checked ListBox Control
Hey, everyone, hope you are doing great. In today's article, we are going to explore
C# Checked ListBox Control. In the previous article, we discussed in details about
C# TextBox,
C# Label,
C# ListBox,
C# ComboxBox and
C# Button. C# Checked ListBox plays very important role in Point Of Sale applications. In some words, we can say this is a combination of check boxes and list. C# Checked ListBox is used to gain specific information from end-user. It's mostly used in survey-based application to gain the voting for a specific purpose.
We will work with Checked ListBox same as we have worked with ListBox & ComboBox. You can use C# Checked ListBox for multiple purposes. You can use this as the attendance taker to mark the attendance of students.
C# Checked ListBox Control
The
C# Checked ListBox is simple list box with the combination of checks. It provides you the list and checks to mark them as you select the items. The user can select the single and multiple checks. According to the need, you can set the checks enabled and disabled. You can create conditional statements on which C# Checked ListBox will become enabled and disabled. When professional programmers used Checked ListBox they will also use the Conditional Statements. They make sure that checked boxes will become enabled only when user will fill up or proceed the above instructions. A live example of checkbox usage is the terms & condition form of any organization. If you are getting started with YouTube they will be asked you to read their terms and checked in the last that you are agreed or not. If you will check the box only then you can process forward. Same is the case will C# Checked ListBox, developers make the conditional check for inputs gained from C# Checked ListBox.
If you are wanted to add the Checked ListBox, then go to the toolbox in design tab. Drag the C# Checked ListBox on the form. Now the CheckListBox is added to the form. The default name of first drag Checked ListBox is as
CheckedListBox1. You can change this name from the property tab on the right-hand side. Supposed you are wanted to add values in C# Checked ListBox, then you have to write items after the default name and select the add method. In the following code, you can be observed how we inserted the values inside C# Checked ListBox.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
We have used the button. When user will click the button, C# Checked ListBox values appears. It depends on your logic that how you wanted to process the codes. I have used the button if you don't want to use the button you can simply copy the code after the InitializeComponent function. It will generate the following output when a button is clicked.
C# Checked ListBox Properties
If you are looking to change the default styles, color scheme, font size etc then there are many properties which you can use to modify the Checked ListBox. Default Checked ListBox is simple in appearance, you can make that attractive by customising the properties. In the following part of an article, we will discuss, how to change foreground color and background color of a checked list box. How to change the font size and make checked and uncheck marks on checked ListBox items.
If you are wanted to make the Checked ListBox items marked check when executing the program, then you have to use the CheckState attribute. There are three values which you can use for CheckState attribute.
- Checked
- UnChecked
- Indeterminate
In the following code, we have used all the above values for CheckState attribute. By default all the Checked ListBox items are UnChecked so you don't need to write the UnChecked values.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add("TEP 1", CheckState.Checked);
checkedListBox1.Items.Add("TEP 2", CheckState.Indeterminate);
checkedListBox1.Items.Add("TEP 3", CheckState.Unchecked);
checkedListBox1.Items.Add("TEP 4");
}
}
}
We don't use the CheckState for the 4th item because by default it's unchecked. If you will execute the code, you observed that Check will be marked, Indeterminate is Check but can't edit and uncheck is unmarked. If you can't understand then the below image will the exact output of the above code.
If you are looking to change the background color then you have to use the backColor property. BackColor property is applicable on all tools which are available in ToolBox. In the following code, we are going to change the background color of Checked ListBox from white to AliceBlue. We will use the Color property to set the color. You can get the idea from the code.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.BackColor = Color.AliceBlue;
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
If you are wanted to change the foreground color or color of the font, then you have to use the ForeColor property to set the colors. We will be used the Color property to set the value of color which is assigned to the foreColor. In the following code, we have used BlueViolet color and set it for the foreground or for the font.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.ForeColor = Color.BlueViolet;
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
If you are wanted to change the font size, then you have to used to set the font property. We have to call the font constructor and passed two parameters. The first parameter is
Font.FontFamily and the second parameter is the size of the font. In the following code, you can observe that how we changed the font size for Checked ListBox. The first parameter is the prototype and the second parameter is the font style property.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Font = new Font(Font.FontFamily, 12);
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
If you are wanted to change the text style into italic, then you have to use the FontStyle property. We have to use the font constructor and passed two parameters. The first parameter is the prototype and the second one is the FontStyle.Value which is set to Italic in the following code. We have passed the CheckedListBox1.Font as the prototype parameter.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Font = new Font(checkedListBox1.Font, FontStyle.Italic);
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
If you are wanted to bold the text, then you have to use the font constructor and passed the Font style as the bold. In the following code, we have changed the text of checkedListBox items to bold.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Font = new Font(checkedListBox1.Font, FontStyle.Bold);
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
If you are wanted to change the font family style then you have to use the font constructor and passed the font family name and size as the parameter. The first parameter is the name of font family and the second parameter is the font size. In the following code, we have used the "Times New Roman" and the size as 20.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Font = new Font("Times New Roman",20);
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
}
}
If you are wanted to check that what the value you have selected, then you have to use the SelectedItem. In the following code, I have used the button and message box to show the selected item value. If you will execute the code, then you have to select the items first then click the button and it returns the selected item value in the message box.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(checkedListBox1.SelectedItem.ToString());
}
}
}
If you are wanted to verify that, which items are marked or check, then you have to use the foreach loop. In the following code, we have used the foreach loop to get the value from checkedListBox1.CheckedItems into an object-based variable which is itemCheck. Then we have to use message box to show the value of itemCheck in each step of a loop by converting the object type value into a string by calling the ToSting method.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void button1_Click(object sender, EventArgs e)
{
foreach (object itemChecked in checkedListBox1.CheckedItems)
{
MessageBox.Show(itemChecked.ToString());
}
}
}
}
If you are wanted to change the border style of Checked ListBox, then you have to use the BorderStyle property and set the style according to your need. There are three styles which you can apply, all those styles are mention in the following code. You can check them one by one, if you will execute all of these styles at once then only the last one is getting executed and other above will get ignored by the compiler.
checkedListBox1.BorderStyle = BorderStyle.Fixed3D;
checkedListBox1.BorderStyle = BorderStyle.FixedSingle;
checkedListBox1.BorderStyle = BorderStyle.None;
C# Checked ListBox Events
C# provides various events to utilize with GUI tools. We can be used events to Checked ListBox and enhanced its features. Events are introduced to create conditional checks for the users to perform specific functionalities at specific times. You can change any attribute when user will click on the listed or checked items. Changed the color when items mark checked. It depends on the requirement of the software in which you will use the CheckedListBox. Following are some events which we are going to demonstrate with Checked ListBox.
- Checked ListBox Click Event
- Checked ListBox MouseHover Event
- Checked ListBox MouseLeave Event
- Checked ListBox BackColorChanged Event
- Checked ListBox ForeColorChanged Event
- Checked ListBox FontChanged Event
There are many other events, which we can use. Each event has its own logic of occurrence. Some events are common across the GUI Tools and some events are specifically used by GUI Tools.
Checked ListBox Click Event
This event will be executed when the user clicks within the boundaries of Checked ListBox. Whatever user will click on any listed item, checkbox or border it will get executed. To get the concept of the click event, suppose that you are wanted when someone clicks on CheckedListBox then the message will pop up and show notification of click. In the following program, we have created the code, which can execute in your compiler too.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void checkedListBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("You have Clicked !!");
}
}
}
An output of the above code is given in the following image. You can perform any functionality as you required. For the demonstration purpose just used the message box to reflect any action.
In the above code, we have to use the click event, if you want to activate the click event then simply click on the CheckedListBox in the design tab and it will create automatically click function. There is another option to do this, first, create any simple function and then set that function to the click event. In the following image, you can observe that when you click on CheckedListBox _Click function is set to click event.
Checked ListBox MouseHover Event
This event will be executed when mouse will hover the boundaries of Checked ListBox. To clear the concept in the following code we are going to perform mousehover function. When user will hover the mouse on the boundaries event will get executed and show the message popup.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void checkedListBox1_MouseHover(object sender, EventArgs e)
{
MessageBox.Show("Mouse is Hover !!");
}
}
}
The above function is builtin and if you want to set the user define function then you can set by your own in the event property. You can perform any kind of functionality, we have used the message box, if you wanted to change anything then you can change such as the color, font family, and size of the text. In the following image, you can view the output of the above code.
Checked ListBox MouseLeave Event
This event will be executed when the cursor of the mouse will leave the boundaries of Checked ListBox. Once you have to hover the boundaries and slightly left the boundaries suddenly the popup shown on the screen and remind you that MouseLeave Event is get executed. In the following code, you can be observed the above concept.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void checkedListBox1_MouseLeave(object sender, EventArgs e)
{
MessageBox.Show("Mouse is Leave !!");
}
}
}
MouseLeave is the default function which you can use after the name of CheckedListBox object name. You can set any user define function also as the alternative of the default function. When you will click the button it will be inserted the values in the CheckedListBox and when you hover the mouse cursor and leave the boundaries it will be executed the MouseLeave method. If you will not click the button, in this case, MousLeave method worked also. The following image is the screenshot of output.
Checked ListBox BackColorChanged Event
This event will occur when you will change the backColor or Background color of CheckListBox. Supposed you are wanted to perform any functionality when the user changed the backColor. Then we will code the functionality in the builtin BackColorChanged event. Instead of performing any functionality we are going to show a message box. In the following code, you can observe we have used the button to change the backColor of checkedListBox. When button will be clicked, the back color will be changed and BackColorChange Event will get executed.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.BackColor = Color.AliceBlue;
}
private void checkedListBox1_BackColorChanged(object sender, EventArgs e)
{
MessageBox.Show("BackColor Is Changed !");
}
}
}
In the above code, we have inserted the values in CheckedListBox during the form initialization phase. Then we have declared the Alice Blue as the backColor of the CheckedListBox within button click event. When user will click on the button, a background color of checkedListBox is get changed and the backColorChanged event gets executed. In the following image, you can preview the output of the above code.
Checked ListBox ForeColorChanged Event
This event is get executed when user will change the ForeColor of CheckedListBox. There are many ways to change ForeColor programmatically. Suppose we have created a button and add instruction to change the ForeColor of CheckListBox. To execute the ForeColor method we have to change the foreColor and best solution is to add foreColor change instruction into button click event. In the following code, you can be observed the above case.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.ForeColor = Color.Red;
}
private void checkedListBox1_ForeColorChanged(object sender, EventArgs e)
{
MessageBox.Show("ForeColor Is Changed !");
}
}
}
In the above code, we have inserted the demo values in the initialization phase of the form. Then we have used the button click event to change the foreColor of the CheckedListBox. Then we have used message box as the functionality which is performed when ForeColor is changed. In the following image, you can observe the output of the above code.
Checked ListBox FontChanged Event
This event will be executed when the font changed. There are several ways to change the fonts, such as you can change the font on the runtime or changed by the events. In the following code, we will create button event and write instruction to change the font the user click. Then used the message box to show interrupt when the font is getting changed. When any kind of change occurs in the font then this event will be executed, whatever you change the font size or font family. In the code, we just change the size of the font for demonstration.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEPNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.Items.Add("TEP 1");
checkedListBox1.Items.Add("TEP 2");
checkedListBox1.Items.Add("TEP 3");
checkedListBox1.Items.Add("TEP 4");
}
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Font = new Font(Font.FontFamily, 12);
}
private void checkedListBox1_FontChanged(object sender, EventArgs e)
{
MessageBox.Show("Font Is Changed !");
}
}
}
If you want to execute above code in your compiler, then you have to drag the button and CheckedListBox. Then activate the button click and FontChanged Event. Then copy paste the above code into a compiler and you will be able to execute the program. Below is the output image of above code.
In this tutorial, we have tried to give you a basic overview of advanced knowledge of C# Checked ListBox. All the above codes are added after the testing. You can do anything with C# Checked ListBox according to your requirements and ideas. If you face any kind of problem let us know. You can also get similar concepts from C# ListBox and
C# ComboBox. You can also get the latest updates of C# Video tutorials from our YouTube Playlist (
C# Video Tutorials). Don't forget to share it with your friends.
C# CheckBox Control
Hello, everyone, I hope you are doing great. In this tutorial, I am going to explain you about C# checkbox control, in my previous tutorials I have already explain you, C# RadioButton Control, C# ListBox Control, C# Button Control and C# Checked ListBox Control. C Sharp checkboxes have their own values in point of sale mission and desktop application development. Checkboxes are basically used to retrieve the specific data from the user.
C# CheckBox allows the user to give specific input. It's mostly used where we have to retrieve the specific data from the user such as the gender selection, terms and condition agreement, and age-restricted data. You can simply use a single object C# CheckBox or multiple objects it totally depends on your requirement of developing a desktop app.
C# CheckBox Control
C# CheckBox is a simple checkbox along with the text which is the name of the checkbox. It will allow a user to make a multiple and specific selection. If the user will click first time on the checkbox then the small tick sign is marked on a checkbox. When user will click again on the checkbox it will get uncheck. Its mean user can select and deselect the checkbox.
If you want to add the checkbox into your desktop application then you have to simply search for it from a toolbox, available in Visual Studio. Then drag the checkbox to your desktop application. Now you are able to use this checkbox. In the following image, you can observe that we have used 15 checkboxes. We just drag one instance of checkbox and replicate that to 14 Times.
You will observe that each checkbox have the default name such as checkbox1, checkbox2, checkbox 3 and so on. You have two options to change the name of a checkbox. The first method is that go to the design tab, click on any of the checkboxes. On the right bottom, the property tab gets activate from where you can change the text of checkbox. In the following image, you can observe the property tab from where you can change the text of checkboxes.
The second method is to change the name programmatically. You can access the same properties which are available in property tab with the help of programming attributes. Programmatically change the name of checkboxes we have to use text property. In the following code, we have used text property and assign a string value. A string value now becomes the text of checkbox when desktop application is executed.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.Text = "TEP CheckBox1";
checkBox2.Text = "TEP CheckBox2";
checkBox3.Text = "TEP CheckBox3";
checkBox4.Text = "TEP CheckBox4";
checkBox5.Text = "TEP CheckBox5";
}
}
}
In the above code, you have observed that we have used text property right after initializecomponent() method. Because we are setting checkbox text dynamically and it will only happen when we will declare this code in the initialization phase of a desktop application. In the following image, you can observe the output of above code.
C# CheckBox Properties
There are several propertie are available, which you can override. In this section, we will discuss all those properties which we can be used to customize C# CheckBox. Such as the Text Color, Text Size, Text Font family etc. The default tools are looks very simple and common. To increase the interactivity of the user we have to create attractive applications and forms. For this purpose, we have to override the default properties.
Supposed that you are wanted, if the program is executed Checkbox is by default marked checked. Then we will use the Checked property to mark it true. In the following code, you can observe that we have used three checkboxes to marked them true.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.Checked = true;
checkBox2.Checked = true;
checkBox3.Checked = true;
}
}
}
In the above code, we only marked check first three checkboxes. By this, you can mark check and uncheck the checkboxes by default. In the following image, you can observe the output of above code.
Supposed that you are wanted to change the background color of Checkbox. Then you have to use the backColor property available for CheckBox. There are many colors available which you can easily be used for your checkboxes. In the following code, you can be observed the different color for each of the checkboxes.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.BackColor = Color.AliceBlue;
checkBox2.BackColor = Color.Beige;
checkBox3.BackColor = Color.BlueViolet;
checkBox4.BackColor = Color.BurlyWood;
checkBox5.BackColor = Color.DarkBlue;
checkBox6.BackColor = Color.DarkOrange;
checkBox7.BackColor = Color.DeepSkyBlue;
checkBox8.BackColor = Color.Gainsboro;
checkBox9.BackColor = Color.LawnGreen;
checkBox10.BackColor = Color.LightSeaGreen;
}
}
}
There are ten checkboxes in the above code, each checkbox has a unique color. Color combination is the major part of designing phase. The client basically focused on the front end of the desktop app that's why coloring matters a lot. In the following image, you can be observed that what right color mean to the eye and whats the wrong color means to an eye, its the output of above code.
Supposed you are wanted to change the color of font or the foreground then you have to use the ForeColor property. By using the ForeColor property we can change the font color. By using the BackColor we have changed the background color and ForeColor property is the inverse. In the following code we just simply changed the BackColor into ForeColor and all the above color which we used for the background now used as the foreground.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.ForeColor = Color.AliceBlue;
checkBox2.ForeColor = Color.Beige;
checkBox3.ForeColor = Color.BlueViolet;
checkBox4.ForeColor = Color.BurlyWood;
checkBox5.ForeColor = Color.DarkBlue;
checkBox6.ForeColor = Color.DarkOrange;
checkBox7.ForeColor = Color.DeepSkyBlue;
checkBox8.ForeColor = Color.Gainsboro;
checkBox9.ForeColor = Color.LawnGreen;
checkBox10.ForeColor = Color.LightSeaGreen;
}
}
}
In the above code, some colors are very light in shade and some are dark. We can't judge the color by their names. Because there are many colors to be used. If you want to select any color then you can to try all the color first. In the following image, you can observe the output of the above code. Some colors are the light that's why you can't clearly saw the output.
Supposed that you are wanted to change the size of the checkbox text. Then you have to use the font property to assign the text size. We will be used font constructor and passed the two parameters. The first parameter is the prototype and second is the size. In the following code, you can be observed how we set the font size for checkboxes.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.Font = new Font(Font.FontFamily, 5);
checkBox2.Font = new Font(Font.FontFamily, 6);
checkBox3.Font = new Font(Font.FontFamily, 7);
checkBox4.Font = new Font(Font.FontFamily, 8);
checkBox5.Font = new Font(Font.FontFamily, 9);
checkBox6.Font = new Font(Font.FontFamily, 10);
checkBox7.Font = new Font(Font.FontFamily, 11);
checkBox8.Font = new Font(Font.FontFamily, 12);
checkBox9.Font = new Font(Font.FontFamily, 13);
checkBox10.Font = new Font(Font.FontFamily, 14);
}
}
}
We have used Font.FontFamily as the prototype and integer value as the size of the font. You can also change the font family by using the font constructor. In the following image, you can observe the output of above code. You will also observe that as much integer value is small the size gets decreased and as much the value is incremented the size get increased.
If you are wanted to change the font family of C# CheckBox text then you have to use the font constructor. We will pass two parameters the first parameter will be a name of font family and the second parameter will be the size of the text. On the note, you must have to know that font constructor does not allow single parameter. In the following code, you can be observed the name of font families.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.Font = new Font("Times New Roman", 11);
checkBox2.Font = new Font("Century", 11);
checkBox3.Font = new Font("Arial", 11);
checkBox4.Font = new Font("Comic Sans MS", 11);
checkBox5.Font = new Font("Copperplate Gothic Light", 11);
checkBox6.Font = new Font("Georgia", 11);
checkBox7.Font = new Font("Impact", 11);
checkBox8.Font = new Font("Lucida Console", 11);
}
}
}
All the above font family names are the default fonts which are available in the windows. If you want to use the special kind of font then you have to install that first before use. You have also mentioned the size along with the font family name. In the following image, you can be observed the output of the above code, and what font effects on the desktop application.
If you are wanted to validate which checkbox is checked or not then you can simply be used the conditional statements. In the following code, I have used the button in which we have used a conditional statement. We used simple checks that which checkbox is marked will return the message box on the button click. When user will check any checkbox and click on the button it will return the message boxes with the named of marked checkboxes.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
MessageBox.Show(checkBox1.Text);
}
if (checkBox2.Checked == true)
{
MessageBox.Show(checkBox2.Text);
}
if (checkBox3.Checked == true)
{
MessageBox.Show(checkBox3.Text);
}
if (checkBox4.Checked == true)
{
MessageBox.Show(checkBox4.Text);
}
if (checkBox5.Checked == true)
{
MessageBox.Show(checkBox5.Text);
}
if (checkBox6.Checked == true)
{
MessageBox.Show(checkBox6.Text);
}
if (checkBox7.Checked == true)
{
MessageBox.Show(checkBox7.Text);
}
if (checkBox8.Checked == true)
{
MessageBox.Show(checkBox8.Text);
}
if (checkBox9.Checked == true)
{
MessageBox.Show(checkBox9.Text);
}
if (checkBox10.Checked == true)
{
MessageBox.Show(checkBox10.Text);
}
}
}
}
You can observe the output of the above code in the following image. In which we have to click the button after the selection of checkbox3 and it returns the message box with its name.
If you are wanted to set any image as the background of C# checkBox then you have to use the image property and have to set the path of an image. In the following code, we are going to set the image for just checkbox1. Remeber that don't use large images for the background because it will disturb your whole layout.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkBox1.Image = Image.FromFile("C:\\Users\\Jade\\Pictures\\brownImage.jpg");
}
}
}
C# CheckBox Event
C# provides many built-in functions which get executed on certain condition. Each condition is nominated as the event. Such as the TextChange Event. When user will change the text of any tool this event is getting executed. We can create a user define functions and assign them to event handlers. There are many events which we can use to enhance the interaction of C# CheckBox. Following are the basic C# CheckBox Events which we will use in a further section of this tutorial.
- C# CheckBox BackColorChanged Event
- C# CheckBox CheckedChanged Event
- C# CheckBox Click Event
- C# CheckBox ForeColorChanged Event
- C# CheckBox MouseHover Event
- C# CheckBox MouseLeave Event
- C# CheckBox TextChanged Event
All the above event have their own condition on which they get executed. In the following part, we will discuss them one by one. We will also create example codes to learn their execution reasons and flow.
C# CheckBox BackColorChanged Event
This event raised when someone changed the background color of Checkbox or change color by any sort of code. The main thing behind the execution of this event is changing the background color. If we create a program in which we first change the color of the background and used this event then it will get executed right after background color gets changed. In the following code, you can get the idea. We have used the button click event handler in which we declared the background color for C# CheckBox. Then we have declared the BackColorChanged Event for C# CheckBox. When user will click on the button, background color gets changed and BackColorChanged Event gets executed.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkBox1.BackColor = Color.AliceBlue;
}
private void checkBox1_BackColorChanged(object sender, EventArgs e)
{
MessageBox.Show("BackColorChanged Executed!");
}
}
}
We have used AliceBlue color for the background. You can use other colors too, there are varieties of colors are available. In the following image, you can observe the output of above code. We have executed just message box when the color changed, you can perform any kind of functionality.
C# CheckBox CheckedChanged Event
This event is get executed when user will be changed the selection. Supposed you have marked check any checkbox and if you uncheck that CheckedChanged event is get executed. Every time you change the selection it will get executed. In the following code, you can observe that we have used CheckedChanged Event just of the checkBox1. So if a user will change the selection of checkbox1 then only it's get executed.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("CheckedChanged Executed!");
}
}
}
You have to create a CheckedChange event for each of the C# CheckBox. We have just created for the first checkBox. In the following image, you can observe that we only mark checked the first checkbox and it returns the message popup.
C# CheckBox Click Event
This event will be executed when user will click on the text or on the checkbox. Supposed that you are wanted to perform any functionality when user will click any specific checkbox then you will be used the Click Event. This event is mostly used with buttons. In the following code you can be observed that we have added this event with the first checkbox so when user will click on the text of the first checkbox or click on the checkbox it will get executed.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("Click Executed!");
}
}
}
In the above code, we just declare click event for checkbox1 only, if you will copy paste it multiple times and rename as checkbox2 and checkbox3 then it would not work. Because you have also assigned the event to the event property which is on the right bottom of visual studio. In the following image, you can be observed the output after execution of the code.
C# CheckBox ForeColorChanged Event
This event is executed when user will change the ForeColor or foreColor is get changed. Supposed if you have created the button click event and declare the foreColor for any specific C# Checkbox and used ForeColorChanged Event just for that specific CheckBox. Then we can execute this event properly. Because on the click of user ForeColor get changed and the ForeColorChanged event gets executed. In the following code, you have observed the above scenario.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkBox1.ForeColor = Color.AliceBlue;
}
private void checkBox1_ForeColorChanged(object sender, EventArgs e)
{
MessageBox.Show("ForeColorChanged Executed!");
}
}
}
When user will click the button, ForeColor of first C# CheckBox is get changed from Black to AliceBlue. After color get changed ForeColorChanged event get executed the return the message popup. In the following image, you can be observed the output that C# CheckBox1 foreColor gets changed.
C# CheckBox MouseHover Event
This event is executed when user will hover the mouse on C# CheckBox. Supposed you are wanted to perform any kind of functionality when user will hover the mouse on CheckBox then you have to use the CheckBox MouseHover event. In the following code, we have used ForeColor to be changed when user will hover the mouse on CheckBox.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkBox1_MouseHover(object sender, EventArgs e)
{
checkBox1.ForeColor = Color.BlueViolet;
MessageBox.Show("ForeColorChanged Executed!");
}
}
}
This is a quite good example to demonstrate the MouseHover event. When user will hover the mouse cursor on the CheckBox1 then ForeColor is get changed into Blue Violet. In the following image, you can get the main idea how it looks after the execution.
C# CheckBox MouseLeave Event
This event is executed when user will hover the mouse and then left the mouse cursor from the boundaries of CheckBox. In short, this event is the inverse of MouseHover event. Now we are going to create animation via MouseLeave and MouseHover event. We will declare the BlueVoilet color for the font when user will hover the mouse and Black color for the font when user will leave the checkBox. Let's have a look at the code and observe its flow of execution.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace strnull
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkBox1_MouseHover(object sender, EventArgs e)
{
checkBox1.ForeColor = Color.BlueViolet;
}
private void checkBox1_MouseLeave(object sender, EventArgs e)
{
checkBox1.ForeColor = Color.Black;
}
}
}
If you want to execute the above code, then you have to drag one checkbox on your windows form. Then add mouse leave and mouse hover event. Copy the above code and inserted into your compiler and executed. When you will hover the mouse on the checkbox1 its font color gets changed and when leaving the checkbox then fore color get to default.
C# CheckBox TextChanged Event
This event is get executed when Text of checkbox is get changed. You can change the text simply write a code. Its depend on your logic and condition of the program. We simply going to change the text when user will click the button. We have used the simple message box to show the prompt that TextChanged event is get executed. In the following code, you can be observed the above scenario.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TEP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkBox1.Text = "Changed !";
}
private void checkBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("Text Changed !!");
}
}
}
For each checkbox, you have to declare the separate TextChanged event handler. In the above code, we declared it just for the checkbox1. So when the default text of checkbox1 is get changed, TextChanged event get raised. In the following image, you can be observed the output.
We have tried to explain you about the C# CheckBox from the beginning to its depth. By using the various examples. We have tried to give the touch of professional usage of events used with C# CheckBox with generic coding. All the above codes are tested first then uploaded, you can also check the executed output in the images which are given right after the codes. If you have any kind of problem regarding C# CheckBox you can share it with us, we will try to resolve your problems at first priority. You can also check our previous tutorials like
C# ListBox Control,
C# Button Control,
C# Label Control and
C# TextBox Control.