Separator
ScrollBar
ScrollViewer
StackPanel
Thumb
Viewbox
VirtualizingStackPanel
Window
WrapPanel
2
Buttons
Buttons are one of the most basic user
interface controls. Applications typically
perform some task in the Click event when a
user clicks on them.
Button
RepeatButton
3
Data Display
Data display controls are used to show
information from a data source.
DataGrid
ListView
TreeView
4
Date Display and Selection
Date controls are used to display and select
calendar information.
Calendar
DatePicker
5
Menus
Menus are used to group related actions or
to provide contextual assistance.
ContextMenu
Menu
ToolBar
6
Selection
Selection controls are used to enable a user
to select one or more options.
CheckBox
ComboBox
ListBox
RadioButton
Slider
7
User Information
User information controls provide
contextual feedback or clarify an
application's user interface. The user
typically cannot interact with these controls.
AccessText
Label
Popup
ProgressBar
StatusBar
TextBlock
ToolTip
8
Common members of list box and combo box
controls
Property
SelectedIndex
SelectedItem
Text
Sorted
Items
Description
The index of the selected item. Items are
numbered from 0. If no item is selected,
this property has a value of -1.
The object of the selected item.
The text value for the selected item.
If set to true, the items in the list are
sorted.
Provides access to the collection of items.
Slide
9
Common members of list box and combo box
controls (continued)
Property
DropDownStyle
SelectionMode
Event
SelectedIndexChanged
TextChanged
Description
Determines whether the user can enter
text in the text box that’s at the top of a
combo box.
Determines whether the user can select
more than one item from a list box.
Description
Occurs when the user selects a different
item from the list.
Occurs when the user enters a value into
the text box portion of a combo box.
Slide
10
Common members of the Items collection
Indexer
[index]
Description
Gets or sets the item at the specified index
in the list.
Description
Gets the number of items in the list.
Description
Adds the specified item to the list.
Inserts an item into the list at the specified
index.
Removes the specified item from the list.
Removes the item at the specified index
from the list.
Removes all items from the list.
Slide
11
Code that loads a combo box with months
string[] months =
{"Select a month...",
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};
foreach (string month in months)
{
cboExpirationMonth.Items.Add(month);
}
Code that loads a combo box with years
int year = DateTime.Today.Year;
int endYear = year + 8;
cboExpirationYear.Items.Add("Select a year...");
while (year < endYear)
{
cboExpirationYear.Items.Add(year);
year++;
}
Slide
12
Code that clears and loads a list box of credit
cards
lstCreditCardType.Items.Clear();
lstCreditCardType.Items.Add("Visa");
lstCreditCardType.Items.Add("Mastercard");
lstCreditCardType.Items.Add("American Express");
lstCreditCardType.SelectedIndex = 0;
// select the first item
Statements that get information from a combo
box or list box
int expYearIndex = cboExpirationYear.SelectedIndex;
string expYearText = cboExpirationYear.Text;
int expYearValue = (int) cboExpirationYear.SelectedItem;
string expMonthValue =
cboExpirationMonth.Items[1].ToString();
Slide
13
Code that works with a combo box of names
string[] names = {"Doug Lowe", "Anne Boehm", "Ed Koop"};
foreach (string name in names)
{
cboNames.Items.Add(name);
}
cboNames.Items.Insert(0, "Joel Murach");
cboNames.Items.RemoveAt(3);
cboNames.SelectedIndex = -1;
// don't select an item
Slide
14
A group box that contains two radio buttons
Common members of radio button and check box
controls
Property
Checked
Event
CheckedChanged
Description
Gets or sets a Boolean value that indicates
whether the control is checked.
Description
Occurs when the user checks or unchecks the
control.
Slide
15
Code that sets the value of a radio button and
check box
rdoCreditCard.Checked = true;
chkDefault.Checked = true;
Code that checks the value of a radio button
private void rdoCreditCard_CheckedChanged(object sender,
System.EventArgs e)
{
if (rdoCreditCard.Checked == true)
EnableControls();
else
DisableControls();
}
Code that gets the value of a check box
bool isDefaultBilling = chkDefault.Checked;
Slide
16
A form in Tab Order view before and after the tab
order is changed
Slide
17
How to use Tab Order view to change the tab
order
To display a form in Tab Order view, select the form and then
select the ViewTab Order command. This displays the tab
index for each control.
To change the tab indexes of the controls, click on the controls in
the sequence you want to use. As you click, the new tab indexes
appear.
If a group box contains other controls, the controls in the group
box are displayed with sub indexes. Then, you can click on the
group box to change its index and the main indexes of the controls
it contains. To change the sub indexes of the controls in the group
box, click on them individually.
Slide
18
Code that creates and displays a custom dialog
box
Form paymentForm = new frmPayment();
paymentForm.ShowDialog();
// execution continues here after the user responds
// to the dialog box
Slide
19
An enumeration that works with dialog boxes
Enumeration
DialogResult
Members
OK, Cancel, Yes, No, Abort, Retry, Ignore, None
The Tag property
Property
Tag
Description
Gets or sets data associated with the form or a
control. The Tag property holds a reference to an
object type, which means that it can hold any type
of data.
Slide
20
A statement that sets the DialogResult property of
a form
this.DialogResult = DialogResult.OK;
A statement that sets the Tag property of a form
this.Tag = msg;
Code that uses the result of a dialog box and the
Tag property
Form paymentForm = new frmPayment();
DialogResult selectedButton = paymentForm.ShowDialog();
if (selectedButton == DialogResult.OK)
lblPayment.Text = paymentForm.Tag.ToString();
Slide
21
How to use the DialogResult enumeration
The DialogResult enumeration provides members that represent
the values that a dialog box can return. The ShowDialog method
returns a member of this enumeration.
You specify the result value of a custom dialog box by setting its
DialogResult property. Or, you can set the DialogResult property
of a button in the dialog box. Then, when the user clicks that
button, the DialogResult property of the form is set accordingly.
If you set the CancelButton property of a form to a button on that
form, the DialogResult property of that button is automatically set
to Cancel.
After you set the DialogResult property of a dialog box, the form
is closed and control is returned to the form that displayed it. If
you close a dialog box without setting the DialogResult property,
a value of Cancel is returned to the main form.
Slide
22
How to use the Tag property
The Tag property provides a convenient way to pass data between
forms in a multi-form application.
A dialog box can set its Tag property before it returns control to
the main form. Then, the main form can get the data from this
property and use it as necessary.
Because the Tag property is an object type, you must explicitly
cast it to the appropriate type to retrieve the data it contains. Or,
you can use the ToString method to convert the data to a string.
Slide
23
The syntax for the Show method of the
MessageBox class
MessageBox.Show(text[, caption [, buttons[, icon[,
defaultButton]]]]);
The enumerations that work with the MessageBox
class
Enumeration
MessageBoxButtons
MessageBoxIcon
A statement that displays a dialog box and gets
the user response
DialogResult button =
MessageBox.Show(
"Are you sure you want to save this data?",
"Payment",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
The dialog box that’s displayed
Slide
25
A statement that checks the user response
to the Payment dialog box
if (button == DialogResult.Yes)
{
SaveData();
isDataSaved = true;
}
Slide
26
The code for a dialog box that cancels the Closing event
private void frmCustomer_FormClosing(object sender,
FormClosingEventArgs e)
{
if (isDataSaved == false)
{
string message =
"This form contains unsaved data.\n\n" +
"Do you want to save it?";
DialogResult button =
MessageBox.Show(message, "Customer",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (button == DialogResult.Yes)
{
if (IsValidData())
this.SaveData();
The dialog box that’s displayed by this code
else
e.Cancel = true;
}
if (button == DialogResult.Cancel)
{
e.Cancel = true;
}
}
}
Slide
27
28
Validation Walk Through
Slide
29
Setting up Messages and Using
string goodMessage;
goodMessage = "";
string badMessage;
badMessage = "";
Validating text and setting focus on 1st error
if (txtFirstName.Text !="")
{
goodMessage += "\n Your First Name is: " + txtFirstName.Text;
}
else
{
badMessage+="\n Please Enter your First Name";
txtFirstName.Focus();
}
if (txtLastName.Text != "")
{
goodMessage += "\n Your Last Name is: " + txtLastName.Text;
}
else
{
if(badMessage == "")
{
txtLastName.Focus();
}
badMessage += "\n Please Enter your Last Name";
}
if (txtEmail.Text != "")
{
goodMessage += "\n Your Email is: " + txtEmail.Text;
}
else
{
if(badMessage == "")
{
txtEmail.Focus();
}
badMessage += "\n Please Enter your Email Address";
}
After each section,
test both good and
bad
31
Validating Radio Buttons No Focus
if (radBlack.IsChecked==true | radBlue.IsChecked == true | radRed.IsChecked==true)
{
if (radBlack.IsChecked == true)
{
goodMessage += "\n your Favourite colour is: " + radBlack.Content;
}
if (radRed.IsChecked == true)
{
goodMessage += "\n your Favourite colour is: " + radRed.Content;
}
if (radBlue.IsChecked == true)
{
goodMessage += "\n your Favourite colour is: " + radBlue.Content;
}
}
else
{
badMessage += "\n You have missed Clicking on your Favourite Colour";
}
if (scrAge.Value > 10)
{
goodMessage += "\n Your age is: " + scrAge.Value;
}
else
{
badMessage += "\n Please Click on scroll to enter your age";
}
34
Checkbox Validation
if (chkFemale.IsChecked==true)
{
goodMessage += "\n You are a Female";
}
else if (chkMale.IsChecked == true)
{
goodMessage += "\n You are a Male";
}
else
{
badMessage += "\n Please Check whether you are male or Female";
}
35
ListBox
//Checking ListBox
if (lstMovie.SelectedIndex < 1)
{
badMessage += "\n Please Select a Movie";
}
else
{
// lstMovie.SelectedItem returns an object. We must cast the
// SelectedItem return object to ListBoxItem, and then we can get to the
// string inside the ListBoxItem, which is stored within its Content.
// Content returns an object, so we must cast that to a string.
// Fortunately, concatenation (the + sign) automatically casts the
// object to a string for us.
goodMessage += "\n You have selected " +
((ListBoxItem)lstMovie.SelectedItem).Content + " for your Movie";
36
}
ComboBox
//Checking Combo Box
if (cboFruit.SelectedIndex < 1)
{
badMessage += "\n Please Select a Fruit";
}
else
{
goodMessage += "\n You have selected " + cboFruit.Text + " for your Fruit";
}
37
38
// Set the allButtons_Click event to all buttons in the Designer
// This is can be done by clicking the Lightning Bolt in the Properties
// window.
private void allButtons_Click(object sender, EventArgs e)
{
// sender is the source object
if (sender is Button)
{
// Cast the sender to a button and assign it to sourceButton
Button sourceButton = (Button)sender;
}
}
39
Streamwriter outputfile;
If (!File.Exists(fileName))
{
outputfile = File.CreateText(fileName);
outputfile.writeline(“Put some text here”);
outputfile.writeline(“if you want, put more here”);
outputfile.close();
}
Else
outputfile = File.AppendText(fileName);
outputfile.writeline(“Put some text here”);
outputfile.writeline(“if you want, put more here”);
outputfile.close();
}
40
Public bool dummy_proof(string str)
{
bool fool = false;
int num;
// You may TryParse as any number type
// (int, double, decimal, etc.)
bool isNum = int.TryParse(str,out num);
if (!isNum)
{
fool = true;
}
else if (str == “0”)
{
fool = true;
}
return fool;
}
private void Form1_Load(object sender, EventArgs e)
{
Button[,] seat = new Button[4, 15];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 15; j++)
{
seat[i, j] = new Button();
seat[i, j].BackColor = Color.Red;
seat[i, j].Size = new Size(20, 20);
seat[i, j].Location = new Point(i * 20 + 20, 30 * j + 30);
seat[i, j].Click += new EventHandler(seat_Click);
seat[i, j].Name = i.ToString() + j.ToString();
seat[i, j].Tag = " ";
Controls.Add(seat[i, j]);
}
}
}
43
Button array Sample
44
private void btnClear_Click(object sender, EventsArgs e)
{
// The first string is the text of the message box, the second
// string is the title, and the
// third argument indicates the buttons shown on the message
// box
DialogResult result1 = MessageBox.Show(
“Are you sure you want to clear the current order?”,
“Important Message”, MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
if (txtShirtPrice.Text != “ ”)
{
total -= current;
}
}
}
45
//Reverses the input
else if (radReverse.Checked == true)
{
char[] reversed = input.Reverse().ToArray();
string checkSameReverse = "";
txtOutput.Clear();
if (reversed != txtInput.Text.ToArray())
{
foreach (char chr in reversed)
{
checkSameReverse += chr.ToString();
}
if (checkSameReverse == txtInput.Text)
{
txtOutput.Text = "It's the same backwars and forwards!";
}
else
{
txtOutput.Text = checkSameReverse;
}
}
}
46
You first need to create a separate Window class. This will define the
separate window your MainWindow will interact with.
In Visual Studio we can
easily add another window
by right clicking on our
Project, choosing Add, then
Window.
In the Add New Item window
that appears, choose
"Window (WPF)" and give it
a name.
47
// Display another WPF window a dialog window. Only the new
// window can then be interacted with. Code in the original window
// stops until the dialog window is closed.
// Create instance of the custom Window class created (in this
// example the class is named Window2) using the default constructor
Window2 popUpWindow = new Window2();
popUpWindow.ShowDialog();
// Display it as another window
// Code continues to run in the original window
popUpWindow.Show();
48
If we wish to pass information from our first window to the newly created window, we can do this
by passing arguments within the new window creation line of code (its constructor)
// The following code would be in the
// MainWindow class
// The following code would be in the
// Window2 class
// Create instance of the Window2 class using a
// non-default constructor (one that takes a string
// as input)
Window2 popUpWindow = new Window2("Hello World!");
popUpWindow.ShowDialog();
// Default Constructor
public Window2()
{
InitializeComponent();
}
// Overloaded Constructor
public Window2(string input)
{
InitializeComponent();
// Do something with the parameter
// For example:
messageLabel.Content = input;
}
49
If we wish to pass information from the Dialog window back to the window it was launched from,
we must utilize properties of the class. In our created Window2 class, we would need to create the
required property.
// The following code would be in the
// The following code would be in the
// Window2 class
// MainWindow class
// Private variable to hold data
// Create instance of the Window2 class using
private string passedString;
// the default constructor
Window2 popUpWindow = new Window2();
// Public Property to expose data to outside Classes
public string PassedString
// Show the instance of the Window, only return
{
// to MainWindow when the instance is closed
get { return passedString; }
popUpWindow.ShowDialog();
set { passedString = value; }
// value is a keyword that references the value
// Set the a textbox within our MainWindow to
// that client code is attempting to assign to the
// the value entered on Window2 instance
// property
outputTextBox.Text = popUpWindow.PassedString; }
// Example get, from another Class
// (e.g. from MainWindow)
// string whatever = popUpWindow.PassedString;
// Example set
// popUpWindow.PassedString = "Whatever";
50
// The value keyword would reference "Whatever"
If you have to create a wait list, use a Queue instead of a
List.
Queues are first in, first out lists.
Queue<string> seatWaitList = new Queue<string>();
// To add to a queue:
seatWaitList.Enqueue(“A name”);
// To remove from a queue:
seatWaitlist.Dequeue();
51
52
Each button has a tag property. This property can hold anything.
However, if you set the tag in the designer it can only be a string. In
this example I’ve assigned a Seat object to each button
// Create a Seat
Seat seatA1 = new Seat();
// Assign the seat to the button
btnMyButton.Tag = seatA1;
// Access the Seat
if (btnMyButton.Tag is Seat) // Make sure the tag is a seat
{
buttonsSeat = (Seat)btnMyButton.Tag; // Cast the Tag to a Seat
// You can now access the Seat assigned to the button
}
53
54
FOCUS OF FIRST ERROR
if (!errorMessage)
{
txtFirst.SelectAll();
txtFirst.Focus();
}
private void cboMonth_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ // From Zack
//Declare variables. Most months have 31 days, run with that as a base.
int dayCount = 31;
int tempDay = cboDay.SelectedIndex + 1;
if (cboMonth.SelectedValue.ToString() == "February")
{
dayCount = 28;
}
else if (cboMonth.SelectedValue.ToString() == "September" || cboMonth.SelectedValue.ToString() == "April" ||
cboMonth.SelectedValue.ToString() == "June" || cboMonth.SelectedValue.ToString() == "November")
{
dayCount = 30;
}
//Clear cboDay, and re-add the right number of days based on the month.
cboDay.Items.Clear();
for (int day = 1; day <= dayCount; day++)
{
cboDay.Items.Add(day);
}
//Slightly messy.
//Retains the previously chosen day. If the chosen day was greater
//than the amount of days in the new month, we'd have a problem.
//Tackle that problem.
if ((dayCount - tempDay) >= 0)
{
cboDay.SelectedIndex = tempDay - 1;
}
else if(dayCount == 30)
{
cboDay.SelectedIndex = 29;
}
else
{
cboDay.SelectedIndex = 27;
}