Windows Programming
Windows Programming
A radio button or option button enables the user to select a single option
from a group of choices when paired with other RadioButton controls. When
a user clicks on a radio button, it becomes checked, and all other radio
buttons with same group become unchecked
The RadioButton control can display text, an Image, or both. Use the
Checked property to get or set the state of a RadioButton.
radioButton1.Checked = true;
The radio button and the check box are used for different functions. Use a
radio button when you want the user to choose only one option. When you
want the user to choose all appropriate options, use a check box. Like check
boxes, radio buttons support a Checked property that indicates whether the
radio button is selected.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# CheckBox Control
CheckBoxes allow the user to make multiple selections from a number of
options. CheckBox to give the user an option, such as true/false or yes/no.
You can click a check box to select it and click it again to deselect it.
The CheckBox control can display an image or text or both. Usually
CheckBox comes with a caption, which you can set in the Text property.
checkBox1.Text = "Net-informations.com";
You can use the CheckBox control ThreeState property to direct the control
to return the Checked, Unchecked, and Indeterminate values. You need to
set the check boxs ThreeState property to True to indicate that you want it
to support three states.
checkBox1.ThreeState = true;
The radio button and the check box are used for different functions. Use a
radio button when you want the user to choose only one option.When you
want the user to choose all appropriate options, use a check box. The
following C# program shows how to find a checkbox is selected or not.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
if (checkBox1.Checked == true)
{
msg = "net-informations.com";
}
if (checkBox2.Checked == true)
{
msg = msg + " vb.net-informations.com";
}
if (checkBox3.Checked == true)
{
msg = msg + " csharp.net-informations.com";
}
if (msg.Length > 0)
{
MessageBox.Show (msg + " selected ");
}
else
{
MessageBox.Show ("No checkbox selected");
}
checkBox1.ThreeState = true;
}
}
}
C# TextBox Control
A TextBox control is used to display, or accept as input, a single line of text.
This control has additional functionality that is not found in the standard
Windows text box control, including multiline editing and password character
masking.
A text box object is used to display text on a form or to get user input while
a C# program is running. In a text box, a user can type data or paste it into
the control from the clipboard.
For displaying a text in a TextBox control , you can code like this
textBox1.Text = "http://csharp.net-informations.com";
You can also collect the input value from a TextBox control to a variable like
this way
string var;
var = textBox1.Text;
C# TextBox Properties
textBox1.Width = 250;
textBox1.Height = 50;
You can set background color and foreground color through property window
and programmatically.
textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;
Textbox BorderStyle
You can set 3 different types of border style for textbox, they are None,
FixedSingle and fixed3d.
textBox1.BorderStyle = BorderStyle.Fixed3D;
TextBox Events
Keydown event
You can capture which key is pressed by the user using KeyDown event
e.g.
TextChanged Event
When user input or setting the Text property to a new value raises the
TextChanged event
e.g.
Sets the maximum number of characters or words the user can input into
the text box control.
textBox1.MaxLength = 40;
Textbox ReadOnly
When a program wants to prevent a user from changing the text that
appears in a text box, the program can set the controls Read-only property
is to True.
textBox1.ReadOnly = true;
Multiline TextBox
You can use the Multiline and ScrollBars properties to enable multiple lines of
text to be displayed or entered.
textBox1.Multiline = true;
TextBox controls can also be used to accept passwords and other sensitive
information. You can use the PasswordChar property to mask characters
entered in a single line version of the control
textBox1.PasswordChar = '*';
The above code set the PasswordChar to * , so when the user enter
password then it display only * instead of typed characters.
or
int i;
i = int.Parse (textBox1.Text);
Parse method Converts the string representation of a number to its integer
equivalent.
float i;
i = float.Parse (textBox1.Text);
double i;
i = float.Parse (textBox1.Text);
Many of us have faced a situation where we want the user to enter a number
in a TextBox. Click the following link that are going to make a Numeric
Textbox which will accept only numeric values; if there are any values
except numeric. More about.... How do I make a textbox that only accepts
numbers
Autocomplete TextBox
From the following C# source code you can see some important property
settings to a TextBox control.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# TextBox Control
A TextBox control is used to display, or accept as input, a single line of text.
This control has additional functionality that is not found in the standard
Windows text box control, including multiline editing and password character
masking.
A text box object is used to display text on a form or to get user input while
a C# program is running. In a text box, a user can type data or paste it into
the control from the clipboard.
For displaying a text in a TextBox control , you can code like this
textBox1.Text = "http://csharp.net-informations.com";
You can also collect the input value from a TextBox control to a variable like
this way
string var;
var = textBox1.Text;
C# TextBox Properties
The below code set a textbox width as 250 and height as 50 through source
code.
textBox1.Width = 250;
textBox1.Height = 50;
textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;
Textbox BorderStyle
You can set 3 different types of border style for textbox, they are None,
FixedSingle and fixed3d.
textBox1.BorderStyle = BorderStyle.Fixed3D;
TextBox Events
Keydown event
You can capture which key is pressed by the user using KeyDown event
e.g.
TextChanged Event
When user input or setting the Text property to a new value raises the
TextChanged event
e.g.
Textbox Maximum Length
Sets the maximum number of characters or words the user can input into
the text box control.
textBox1.MaxLength = 40;
Textbox ReadOnly
When a program wants to prevent a user from changing the text that
appears in a text box, the program can set the controls Read-only property
is to True.
textBox1.ReadOnly = true;
Multiline TextBox
You can use the Multiline and ScrollBars properties to enable multiple lines of
text to be displayed or entered.
textBox1.Multiline = true;
TextBox controls can also be used to accept passwords and other sensitive
information. You can use the PasswordChar property to mask characters
entered in a single line version of the control
textBox1.PasswordChar = '*';
The above code set the PasswordChar to * , so when the user enter
password then it display only * instead of typed characters.
How to Newline in a TextBox
or
int i;
i = int.Parse (textBox1.Text);
float i;
i = float.Parse (textBox1.Text);
double i;
i = float.Parse (textBox1.Text);
Many of us have faced a situation where we want the user to enter a number
in a TextBox. Click the following link that are going to make a Numeric
Textbox which will accept only numeric values; if there are any values
except numeric. More about.... How do I make a textbox that only accepts
numbers
Autocomplete TextBox
From the following C# source code you can see some important property
settings to a TextBox control.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# ListBox Control
The ListBox control enables you to display a list of items to the user that the
user can select by clicking.
In addition to display and selection functionality, the ListBox also provides
features that enable you to efficiently add items to the ListBox and to find
text within the items of the list. You can use the Add or Insert method to
add items to a list box. The Add method adds new items at the end of an
unsorted list box.
listBox1.Items.Add("Sunday");
If you want to retrieve a single selected item to a variable , you can code
like this
string var;
var = listBox1.Text;
The SelectionMode property determines how many items in the list can be
selected at a time. A ListBox control can provide single or multiple selections
using the SelectionMode property . If you change the selection mode
property to multiple select , then you will retrieve a collection of items from
ListBox1.SelectedItems property.
listBox1.SelectionMode = SelectionMode.MultiSimple;
The following C# program initially fill seven days in a week while in the form
load event and set the selection mode property to MultiSimple. At the Button
click event it will display the selected items.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Sunday");
listBox1.Items.Add("Monday");
listBox1.Items.Add("Tuesday");
listBox1.Items.Add("Wednesday");
listBox1.Items.Add("Thursday");
listBox1.Items.Add("Friday");
listBox1.Items.Add("Saturday");
listBox1.SelectionMode = SelectionMode.MultiSimple;
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Object obj in listBox1.SelectedItems )
{
MessageBox.Show(obj.ToString ());
}
}
}
}
First you should create a fresh List Object and add items to the List.
The next step is to bind this List to the Listbox. In order to do that you
should set datasource of the Listbox.
listBox1.DataSource = nList;
Full Source code
First you should create a connection string and fetch data from database to a
Dataset.
listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
//connetionString = "Data Source=ServerName;Initial
Catalog=databasename;User ID=userid;Password=yourpassword";
//sql = "select au_id,au_lname from authors";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
}
}
When you want to clear the Listbox, if the ListBox already binded with
Datasource, you have to set the Datasource of Listbox as null.
listBox1.DataSource = null;
This event is fired when the item selection is changed in a ListBox. You can
use this event in a situation that you want select an item from your listbox
and accodring to this selection you can perform other programming needs.
You can add the event handler using the Properties Window and selecting
the Event icon and double-clicking on SelectedIndexChanged as you can see
in following image.
The event will fire again when you select a new item. You can write your
code within SelectedIndexChanged event . When you double click on ListBox
the code will automatically come in you code editor like the following image.
From the following example you can understand how to fire the
SelectedIndexChanged event
First you should drag two listboxes on your Form. First listbox you should set
the List as Datasource, the List contents follows:
When you load this form you can see the listbox is populated with List and
displayed first quarter and second quarter. When you click the "Fist Quarter"
the next listbox is populated with first quarter months and when you click
"Second Quarter" you can see the second listbox is changed to second
quarter months. From the following program you can understand how this
happened.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Collections.Generic;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List < string > fQ = new List < string > ();
List < string > sQ = new List < string > ();
sQ.Add("April");
sQ.Add("May");
sQ.Add("June");
List < string > nList = new List < string > ();
nList.Add("First Quarter");
nList.Add("Second Quarter");
listBox1.DataSource = nList;
}
}
}
You can add individual items to the list with the Add method. The
CheckedListBox object supports three states through the CheckState
enumeration: Checked, Indeterminate, and Unchecked.
checkedListBox1.Items.Add("Sunday", CheckState.Checked);
checkedListBox1.Items.Add("Monday", CheckState.Unchecked);
checkedListBox1.Items.Add("Tuesday", CheckState.Indeterminate);
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# PictureBox Control
The Windows Forms PictureBox control is used to display images in bitmap,
GIF , icon , or JPEG formats.
You can set the Image property to the Image you want to display, either at
design time or at run time. You can programmatically change the image
displayed in a picture box, which is particularly useful when you use a single
form to display different pieces of information.
pictureBox1.Image = Image.FromFile("c:\\testImage.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
There are five different PictureBoxSizeMode is available to PictureBox
control.
C# ProgressBar Control
A progress bar is a control that an application can use to indicate the
progress of a lengthy operation such as calculating a complex result,
downloading a large file from the Web etc.
Minimum : Sets the lower value for the range of valid values for progress.
Maximum : Sets the upper value for the range of valid values for progress.
Value : This property obtains or sets the current level of progress.
By default, Minimum and Maximum are set to 0 and 100. As the task
proceeds, the ProgressBar fills in from the left to the right. To delay the
program briefly so that you can view changes in the progress bar clearly.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
progressBar1.Minimum = 0;
progressBar1.Maximum = 200;
}
}
C# ScrollBars Control
A ScrollBar allows you to view content that is outside of the current viewing
area by sliding the Thumb to make the content visible.
The ScrollBar control contains a Track control. The Track control consists of
a Thumb control and two RepeatButton controls. You can increase and
decrease the Value property of the ScrollBar control by pressing the
RepeatButton controls or by moving the Thumb. You can set the Value
property yourself in code, which moves the scroll box to match. The
Minimum and Maximum properties determine the range of values that the
control can display. The default range of values for the Value property is
from 0 to 1.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
The DateTimePicker control has two parts, a label that displays the selected
date and a popup calendar that allows users to select a new date. The most
important property of the DateTimePicker is the Value property, which holds
the selected date and time.
dateTimePicker1.Value = DateTime.Today;
The Value property contains the current date and time the control is set to.
You can use the Text property or the appropriate member of Value to get
the date and time value.
DateTime iDate;
iDate = dateTimePicker1.Value;
The control can display one of several styles, depending on its property
values. The values can be displayed in four formats, which are set by the
Format property: Long, Short, Time, or Custom.
dateTimePicker1.Format = DateTimePickerFormat.Short;
Convert String to DateTime
The following C# program shows how to set and get the value of a
DateTimePicker1 control.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
listView1.Columns.Add("ProductName", 100);
You can add items in listbox using ListViewItem which represents an item in
a ListView control.
productName = listView1.SelectedItems[0].SubItems[0].Text;
Above code will return the itme from first column of first row.
If the Sorted property of Listview is set to true, then the ListView items are
sorted. The following code sorts the ListView items:
ListView1.Sorted = true;
myListView.CheckBoxes = true;
myListView.Columns.Add(text, width, alignment);
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
Finally at the button click event, it will display the selected row values in a
message box.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# Menu Control
A Menu on a Windows Form is created with a MainMenu object, which is a
collection of MenuItem objects. MainMenu is the container for the Menu
structure of the form and menus are made of MenuItem objects that
represent individual parts of a menu.
You can add menus to Windows Forms at design time by adding the
MainMenu component and then appending menu items to it using the Menu
Designer.
After drag the Menustrip on your form you can directly create the menu
items by type a value into the "Type Here" box on the menubar part of your
form. From the following picture you can understand how to create each
menu items on mainmenu Object.
If you need a seperator bar , right click on your menu then go to insert-
>Seperator.
After creating the Menu on the form , you have to double click on each menu
item and write the programs there depends on your requirements. The
following C# program shows how to show a messagebox when clicking a
Menu item.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Any windows can become an MDI parent, if you set the IsMdiContainer
property to True.
IsMdiContainer = true;
The following C# program shows a MDI form with two child forms. Create a
new C# project, then you will get a default form Form1 . Then add two
mnore forms in the project (Form2 , Form 3) . Create a Menu on your form
and call these two forms on menu click event. Click here to see how to
create a Menu on your form How to Menu Control C#.
NOTE: If you want the MDI parent to auto-size the child form you can code
like this.
form.MdiParent = this;
form.Dock=DockStyle.Fill;
form.Show();
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
The following C# program invites a color dialog box and retrieve the selected
color to a string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
The following C# program invites a Font Dialog Box and retrieve the selected
Font Name and Font Size.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
if (dlg.ShowDialog() == DialogResult.OK)
{
string fontName;
float fontSize;
fontName = dlg.Font.Name;
fontSize = dlg.Font.Size;
MessageBox.Show(fontName + " " + fontSize );
}
}
}
}
The following C# program invites an OpenFile Dialog Box and retrieve the
selected filename to a string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
MessageBox.Show(fileName);
}
}
}
}
The Print dialog box includes a Print Range group of radio buttons that
indicate whether the user wants to print all pages, a range of pages, or only
the selected text. The dialog box includes an edit control in which the user
can type the number of copies to print. By default, the Print dialog box
initially displays information about the current default printer.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Win
dowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
keyPress event in C#
Handle Keyboard Input at the Form Level in C#
KeyDown
KeyPress
KeyUp
The following C# code behind creates the KeyDown event handler. If the key
that is pressed is the Enter key, a MessegeBox will displayed .
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Pressed ");
}
KeyDown Event : This event raised as soon as the user presses a key on
the keyboard, it repeats while the user keeps the key depressed.
KeyPress Event : This event is raised for character keys while the key is
pressed and then released. This event is not raised by noncharacter keys,
unlike KeyDown and KeyUp, which are also raised for noncharacter keys
KeyUp Event : This event is raised after the user releases a key on the
keyboard.
KeyPress Event :
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
if (e.KeyChar == 13)
{
MessageBox.Show("Enter key pressed");
}
}
}
}
KeyDown Event :
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
}
}
}
KeyUp Event :
The following C# source code shows how to capture Enter KeyDown event
from a TextBox Control.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Visual Studio .NET does not have control arrays like Visual Basic 6.0 does.
The good news is that you can still set things up to do similar things. The
advantages of C# dynamic controls is that they can be created in response
to how the user interacts with the application. Common controls that are
added during run-time are the Button and TextBox controls. But of course,
nearly every C# control can be created dynamically.
How to create Dynamic Controls in C# ?
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int cLeft = 1;
public Form1()
{
InitializeComponent();
}
C# Timer Control
What is Timer Control ?
Timer example
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString();
}
}
}
The Timer control have included the Start and Stop methods for start and
stop the Timer control functions.
Here we run this program only 10 seconds. In order to doing this ,in the
following program we set Timer interval as 1000 (1 second) and check each
seconds for stopping the Timer Control after 10 seconds.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
int second = 0;
public Form1()
{
InitializeComponent();
}