0% found this document useful (0 votes)
130 views56 pages

Lecture04 - ITE 5230

This document discusses various controls that can be used in Windows forms applications using C#, including combo boxes, list boxes, radio buttons, check boxes, group boxes, and DateTimePickers. It provides code examples for working with these controls and setting their properties. The document also covers displaying forms and dialog boxes in an application.

Uploaded by

Madhav Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views56 pages

Lecture04 - ITE 5230

This document discusses various controls that can be used in Windows forms applications using C#, including combo boxes, list boxes, radio buttons, check boxes, group boxes, and DateTimePickers. It provides code examples for working with these controls and setting their properties. The document also covers displaying forms and dialog boxes in an application.

Uploaded by

Madhav Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

ITE 5230

Windows Application Development using C#.Net


Lecture 4

1
Chapter 10

More skills for working


with Windows forms
and controls

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 2
Objectives
Applied
1. Given the specifications for a form that uses any of the controls
presented in this chapter, design and code the form.
2. Given a form with two or more controls, set the tab order of the
controls using the Tab Order view of the form.
3. Given the specifications for an application that displays custom or
standard dialog boxes, design and code the application.
Knowledge
1. In general terms, describe the use of these controls: combo box, list
box, radio button, check box, and group box.
2. Explain how the refactoring feature helps you change some of the
occurrences of the form name in the code when you rename the file
for the form, but not the occurrences in the event handlers for the
form.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 3
Objectives (cont.)
3. Describe the way the Program class for an application displays the
first form of an application.
4. Describe how you can use the DialogResult enumeration and the
Tag property to pass data between a form and a custom dialog box.
5. Describe how you can use the FormClosing event to stop a form
from closing.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 4
A form with five more types of controls

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 5
Common members of list box
and combo box controls
SelectedIndex
SelectedItem
Text
Sorted
Items
DropDownStyle
SelectionMode

Common events of list box


and combo box controls
SelectedIndexChanged
TextChanged

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 6
Common properties of the Items collection
[index]
Count

Common methods of the Items collection


Add(object)
Insert(index, object)
Remove(object)
RemoveAt(index)
Clear()

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 7
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);
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 8
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++;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 9
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;

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();

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 10
Code that works with a combo box of names
string[] names = {"Judy Taylor", "Anne Boehm", "Kelly Slivkoff"};
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

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 11
A group box that contains two radio buttons

Common property of radio button


and check box controls
Checked

Common event of radio button


and check box controls
CheckedChanged

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 12
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,
EventArgs e)
{
if (rdoCreditCard.Checked == true)
EnableControls();
else
DisableControls();
}

Code that gets the value of a check box


bool isDefaultBilling = chkDefault.Checked;

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 13
A form in Tab Order view
before and after the tab order is changed

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 14
How to use Tab Order view
 To display a form in Tab Order view, select the form and then
select the ViewTab 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.
 The first time you click on a control in Tab Order view, the tab
index is set to the next number in sequence, starting with zero for
the first control. If you click on the same control more than once,
the tab index is increased by one each time you click.
 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.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 15
Help for the DateTimePicker control

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 16
The Add New Item dialog box

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 17
How to add a new form
 Display the Add New Item dialog box by selecting the
ProjectAdd New Item command. Or, select the AddNew
Item command from the shortcut menu that’s displayed when you
right-click on the project in the Solution Explorer.
 To add a new form, select the Windows Form template from the
Add New Item dialog box, enter a name for the form, and click
the Add button.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 18
How to add an existing form
 Display the Add Existing Item dialog box by selecting the
ProjectAdd Existing Item command. Or, select the
AddExisting Item command from the shortcut menu for the
project.
 To add an existing form, select the cs file for the form from the
Add Existing Item dialog box and then click the Open button.
 If the form is in a different namespace than the other forms in the
project, you will need to either change the namespace for the form
or add a using directive for the namespace to each form that refers
to it.
 To change the namespace for a form, display the code for the
form and then change the name on the namespace statement near
the top of the code using refactoring.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 19
The generated code
for a new form named frmPayment
For the frmPayment.cs file
namespace Payment
{
public partial class frmPayment : Form
{
public frmPayment()
{
InitializeComponent();
}
}
}

For the frmPayment.Designer.cs file


namespace Payment
{
partial class frmPayment
{
#region Windows Form Designer generated code
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 20
The code that’s generated
for the Load event handler of the form
The method declaration in the frmPayment.cs file
private void frmPayment_Load(object sender, EventArgs e)
{
// code that handles the event goes here
}

The wiring in the frmPayment.Designer.cs file


this.Load += new System.EventHandler(this.frmPayment_Load);

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 21
A project that contains two forms

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 22
How to change the name of a form
1. Right-click the form in the Solution Explorer and select the Rename
command. Or, select the form in the Solution Explorer and press F2.
2. Enter the new name for the form. When you do, Visual Studio asks
if you want to rename all references to the file. In most cases, that’s
what you’ll want to do.

How to change the name of any event handlers


for a form’s events
1. Highlight the name of the form in the method that’s used by the
event handler, then right-click on the name and choose Rename
from the shortcut menu that’s displayed.
2. Enter the new name for the form and click the Apply button in the
Rename dialog box.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 23
Code that defines the main entry point
for an application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Payment
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmCustomer());
}
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 24
The Payment form displayed as a dialog box

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 25
Properties for creating custom dialog boxes
FormBorderStyle
ControlBox
MaximizeBox
MinimizeBox

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 26
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

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 27
An enumeration that works with dialog boxes
Enumeration Members
DialogResult OK, Cancel, Yes, No, Abort, Retry, Ignore,
None

The Tag property


Property Description
Tag 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.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 28
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();

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 29
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.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 30
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.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 31
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 Members
MessageBoxButtons OK, OKCancel, YesNo,
YesNoCancel, AbortRetryIgnore
MessageBoxIcon None, Information, Error, Warning,
Exclamation, Question, Asterisk,
Hand, Stop
MessageBoxDefaultButton Button1, Button2, Button3
DialogResult OK, Cancel, Yes, No, Abort, Retry,
Ignore

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 32
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

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 33
A statement that checks the user response
if (button == DialogResult.Yes)
{
SaveData();
isDataSaved = true;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 34
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();
else
e.Cancel = true;
}
if (button == DialogResult.Cancel)
{
e.Cancel = true;
}
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 35
The dialog box that’s displayed

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 36
The Customer form

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 37
Two versions of the Payment dialog box

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 38
The property settings for the Customer form
Default name Property Setting
Form1 Name frmCustomer
Text Customer
CancelButton btnExit
StartPosition CenterScreen
comboBox1 Name cboNames
DropDownStyle DropDownList
label3 Name lblPayment
BorderStyle Fixed3D
AutoSize False
Text ""
button1 Name btnSave
button2 Name btnExit
button3 Name btnSelectPayment

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 39
The property settings for the Payment form
Default name Property Setting
Form2 Name frmPayment
Text Payment
AcceptButton btnOK
CancelButton btnCancel
StartPosition CenterScreen
ControlBox False
MaximizeBox False
FormBorderStyle FixedDialog
groupBox1 Text Billing
radioButton1 Name rdoCreditCard
Checked True
radioButton2 Name rdoBillCustomer
listBox1 Name lstCreditCardType
textBox1 Name txtCardNumber

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 40
The property settings for the Payment form
Default name Property Setting
comboBox1 Name cboExpirationMonth
DropDownStyle DropDownList
comboBox2 Name cboExpirationYear
DropDownStyle DropDownList
checkBox1 Name chkDefault
Checked True
button1 Name btnOK
button2 Name btnCancel
DialogResult Cancel

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 41
The code for the Customer form
public partial class frmCustomer : Form
{
public frmCustomer()
{
InitializeComponent();
}

bool isDataSaved = true;

private void frmCustomer_Load(object sender,


EventArgs e)
{
cboNames.Items.Add("Mike Smith");
cboNames.Items.Add("Nancy Jones");
}

private void DataChanged(object sender, EventArgs e)


{
isDataSaved = false;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 42
The code for the Customer form (cont.)
private void btnSelectPayment_Click(object sender,
EventArgs e)
{
Form paymentForm = new frmPayment();
DialogResult selectedButton =
paymentForm.ShowDialog();
if (selectedButton == DialogResult.OK)
{
lblPayment.Text = (string) paymentForm.Tag;
}
}

private void btnSave_Click(object sender, EventArgs e)


{
if (IsValidData())
{
SaveData();
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 43
The code for the Customer form (cont.)
private void SaveData()
{
cboNames.SelectedIndex = -1;
lblPayment.Text = "";
isDataSaved = true;
cboNames.Focus();
}

private bool IsValidData()


{
if (cboNames.SelectedIndex == -1)
{
MessageBox.Show(
"You must select a customer.",
"Entry Error");
cboNames.Focus();
return false;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 44
The code for the Customer form (cont.)
if (lblPayment.Text == "")
{
MessageBox.Show(
"You must enter a payment.",
"Entry Error");
return false;
}
return true;
}

private void btnExit_Click(object sender, EventArgs e)


{
this.Close();
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 45
The code for the Customer form (cont.)
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);

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 46
The code for the Customer form (cont.)
if (button == DialogResult.Yes)
{
if (IsValidData())
this.SaveData();
else
e.Cancel = true;
}
if (button == DialogResult.Cancel)
{
e.Cancel = true;
}
}
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 47
The code for the Payment form
public partial class frmPayment : Form
{
public frmPayment()
{
InitializeComponent();
}

private void Payment_Load(object sender, EventArgs e)


{
lstCreditCardType.Items.Add("Visa");
lstCreditCardType.Items.Add("Mastercard");
lstCreditCardType.Items.Add("American Express");
lstCreditCardType.SelectedIndex = 0;

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);
cboExpirationMonth.SelectedIndex = 0;

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 48
The code for the Payment form (cont.)
int year = DateTime.Today.Year;
int endYear = year + 8;
cboExpirationYear.Items.Add("Select a year...");
while (year < endYear)
{
cboExpirationYear.Items.Add(year);
year++;
}
cboExpirationYear.SelectedIndex = 0;
}

private void btnOK_Click(object sender, EventArgs e)


{
if (IsValidData())
{
this.SaveData();
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 49
The code for the Payment form (cont.)
private bool IsValidData()
{
if (rdoCreditCard.Checked)
{
if (lstCreditCardType.SelectedIndex == -1)
{
MessageBox.Show(
"You must select a credit card type.",
"Entry Error");
lstCreditCardType.Focus();
return false;
}
if (txtCardNumber.Text == "")
{
MessageBox.Show(
"You must enter a credit card number.",
"Entry Error");
txtCardNumber.Focus();
return false;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 50
The code for the Payment form (cont.)
if (cboExpirationMonth.SelectedIndex == 0)
{
MessageBox.Show(
"You must select a month.",
"Entry Error");
cboExpirationMonth.Focus();
return false;
}
if (cboExpirationYear.SelectedIndex == 0)
{
MessageBox.Show(
"You must select a year.",
"Entry Error");
cboExpirationYear.Focus();
return false;
}
}
return true;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 51
The code for the Payment form (cont.)
private void SaveData()
{
string msg = null;
if (rdoCreditCard.Checked == true)
{
msg += "Charge to credit card." + "\n\n";
msg += "Card type: " + lstCreditCardType.Text + "\n";
msg += "Card number: " + txtCardNumber.Text + "\n";
msg += "Expiration date: "
+ cboExpirationMonth.Text + "/"
+ cboExpirationYear.Text + "\n";
}
else
{
msg += "Send bill to customer." + "\n\n";
}

bool isDefaultBilling = chkDefault.Checked;


msg += "Default billing: " + isDefaultBilling;

this.Tag = msg;
this.DialogResult = DialogResult.OK;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 52
The code for the Payment form (cont.)
private void Billing_CheckedChanged(object sender, EventArgs e)
{
if (rdoCreditCard.Checked)
EnableControls();
else
DisableControls();
}

private void EnableControls()


{
lstCreditCardType.Enabled = true;
txtCardNumber.Enabled = true;
cboExpirationMonth.Enabled = true;
cboExpirationYear.Enabled = true;
}

private void DisableControls()


{
lstCreditCardType.Enabled = false;
txtCardNumber.Enabled = false;
cboExpirationMonth.Enabled = false;
cboExpirationYear.Enabled = false;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 53
Exercise 10-2 Enhance the Future Value
application

Add a combo box and a list box to the Future Value


application.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 54
Extra 10-1 Convert lengths

Convert the value the user enters based on the selected


conversion type.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 55
Lab_04

Complete a form that accepts a lunch order and then


calculates the order subtotal and total.

Murach's © 2016, Mike Murach & Associates, Inc.


C10, Slide 56

You might also like