61
C# Introduction ISYS 512

C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Embed Size (px)

Citation preview

Page 1: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

C# Introduction

ISYS 512

Page 2: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Visual Studio 2013 Demo• Start page: New project/ Open project/Recent projects• Starting project:

• File/New Project/– C# – Windows

» Windows form application– Project name/Project folder

• Project windows:– Form design view/Form code view– Solution Explorer

• View/Solution Explorer

– ToolBox– Property Window

• Properties and Events

– Server Explorer– Project/Add New Item– Property window example

Page 3: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Introduction to C#

• Event-driven programming– The interface for a C# program consists of one

or more forms, containing one or more controls (screen objects).

– Form and controls have events that can respond to. Typical events include clicking a mouse button, type a character on the keyboard, changing a value, etc.

– Event procedure

Page 4: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Form

• Properties:– Name, FormBorderStyle, Text, BackColor,

BackImage, Opacity

• Events:– Load, FormClosing, FormClosed– GotFocus, LostFocus– MouseHover, Click, DoubleCLick

Page 5: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Common Controls

• TextBox• Label• Button• CheckBox• RadioButton• ListBox• ComboBox• PictureBox

Page 6: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Text Box• Properties:

– BorderStyle, CauseValidation, Enabled, Locked, Multiline, PasswordChar, ReadOnly, ScrollBar, TabIndex, Text, Visible, WordWrap, etc.

• Properties can be set at the design time or at the run time using code.

• To refer to a property: – ControlName.PropertyName– Ex. TextBox1.Text– Note: The Text property is a string data type and

automatically inherits the properties and methods of the string data type.

Page 7: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Typical C# Programming Tasks

• Creating the GUI elements that make up the application’s user interface.– Visualize the application.– Make a list of the controls needed.

• Setting the properties of the GUI elements

• Writing procedures that respond to events and perform other operations.

Page 8: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

To Add an Event-Procedure

• 1. Select the Properties window

• 2. Click Events button

• 3. Select the event and double-click it.

• Note: Every control has a default event. • Form: Load event

• Button control: Click event

• Textbox: Text Changed event

– To add the default event procedure, simply double-click the control.

Page 9: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Demo

FirstName

LastName

.Control properties

.Event: Click, MouseMove, Form Load, etc.

.Event proceduresFullName: textBox3.Text textBox3.Text = textBox1.Text + " " + textBox2.Text;

Demo: Text alignment (TextBox3.TextAlign=HorizontalAlign.Right)TextBox3.BackColor=Color.Aqua;

Show Full Name

Page 10: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Demo

Num1

Num2

Compute Sum

.Control properties

.Event: Click, MouseMove, Form Load, etc.

.Event proceduresSum: textBox3.Text = (double.Parse(textBox1.Text) + double.Parse(textBox2.Text)).ToString();

In-Class lab: Show the product of Num1 and Num2.

Page 11: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

C# Project

• The execution starts from the Main method which is found in the Program.cs file.– Solution/Program.cs– Contain the startup code

• Example: Application.Run(new Form1());

Page 12: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Variable Names

• A variable name identifies a variable• Always choose a meaningful name for variables• Basic naming conventions are:

– the first character must be a letter (upper or lowercase) or an underscore (_)

– the name cannot contain spaces– do not use C# keywords or reserved words

• Variable name is case sensitive

Page 13: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Declare a Variable• C# is a strongly typed language. This means

that when a variable is defined we have to specify what type of data the variable will hold.

• DataType VaraibleName;• A C# statement ends with “;”

Page 14: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

string DataType

• string Variables: • Examples:

string empName;string firstName, lastAddress, fullName;

• String concatenation: + • Examples:

fullName = firstName + lastName;MessageBox.Show(“Total is “ + 25.75);

Page 15: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Numeric Data Types

• int, double• Examples:

double mydouble=12.7, rate=0.07;int Counter = 0;

Page 16: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Inputting and Outputting Numeric Values

• Input collected from the keyboard are considered combinations of characters (or string literals) even if they look like a number to you

• A TextBox control reads keyboard input, such as 25.65. However, the TextBox treats it as a string, not a number.

• In C#, use the following Parse methods to convert string to numeric data types

– int.Parse– double.Parse

– Examples:int hoursWorked = int.Parse(hoursWorkedTextBox1.Text); double temperature = double.Parse(temperatureTextBox.Text);

Note: We can also use the .Net’s Convert class methods: ToDouble, ToInt, ToDecimal:Example: hoursWorked = Convert.ToDouble(textBox1.Text);

Page 17: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Explicit Conversion between Numeric Data Types with Cast Operators

• C# allows you to explicitly convert among types, which is known as type casting

• You can use the cast operator which is simply a pair of parentheses with the type keyword in it

int iNum1;double dNum1 = 2.5;iNum1 = (int) dNum1;

Note: We can also use the .Net’s Convert class methods

Page 18: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Implicit conversion and explicit conversion

int iNum1 = 5, iNum2 = 10;double dNum1 = 2.5, dNum2 = 7.0;dNum1 = iNum1 + iNum2; /*C# implicitly convert integer to double*/iNum1 = (int) dNum1 * 2; /*from doulbe to integer requires cast operator*/

Page 19: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Performing Calculations

• Basic calculations such as arithmetic calculation can be performed by math operators

Operator Name of the operator Description

+ Addition Adds two numbers

- Subtraction Subtracts one number from another

* Multiplication Multiplies one number by another

/ Division Divides one number by another and gives the quotient

% Modulus Divides one number by another and gives the remainder

Other calculations: Use Math class’s methods.

Page 20: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Example

int dividend, divisor, quotient, remainder; dividend = int.Parse(textBox1.Text); divisor = int.Parse(textBox2.Text); quotient = dividend / divisor; remainder = dividend % divisor; textBox3.Text = quotient.ToString(); textBox4.Text = remainder.ToString();

Note: The result of an integer divided by an integer is integer. For example, 7/2 is 3, not 3.5.

Page 21: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Lab Exercise• Enter length measured in inches in a textbox; then

show the equivalent length measured in feet and inches.

• For example, 27 inches is equivalent to 2 feet and 3 inches.

Page 22: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

FV = PV * (1 +Rate) Year

double pv, rate, years, fv; pv = double.Parse(textBox1.Text); rate = double.Parse(textBox2.Text); years = double.Parse(textBox3.Text); fv = pv*Math.Pow(1 + rate, years); textBox4.Text = fv.ToString();

Page 23: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Formatting Numbers with the ToString Method

• The ToString method can optionally format a number to appear in a specific way

• The following table lists the “format strings” and how they work with sample outputs

Format String

Description Number ToString() Result

“N” or “n” Number format 12.3 ToString(“n3”) 12.300

“F” or “f” Fixed-point scientific format 123456.0 ToString("f2") 123456.00

“E” or “e” Exponential scientific format 123456.0 ToString("e3") 1.235e+005

“C” or “c” Currency format -1234567.8 ToString("C") ($1,234,567.80)

“P” or “p” Percentage format .234 ToString("P") 23.40%

Page 24: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Working with DateTime Data

• Declare DateTime variable:– Example: DateTime mydate;

• Convert date entered in a textbox to DateTime data:– Use Convert:

• mydate = Convert.ToDateTime(textBox1.Text);– Use DateTime class Parse method:

• mydate = DateTime.Parse(textBox1.Text);

• DateTime variable’s properties and methods:– MinValue, MaxValue

Page 25: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

DateTime Example

DateTime myDate;myDate = DateTime.Parse(textBox1.Text);MessageBox.Show(myDate.ToLongDateString());

MessageBox.Show(DateTime.MinValue.ToShortDateString());MessageBox.Show(DateTime.MaxValue.ToShortDateString());

Page 26: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

How to calculate the number of days between two dates?

• TimeSpan class: TimeSpan represents a length of time. Define a TimeSpan variable:

TimeSpan ts;

• We may use a TimeSpan class variable to represent the length between two dates:

ts = laterDate-earlierDate;

Page 27: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Code ExampleDateTime earlierDate, laterDate;double daysBetween;TimeSpan ts;earlierDate = DateTime.Parse(textBox1.Text);laterDate = DateTime.Parse(textBox2.Text);ts = laterDate-earlierDate;daysBetween = ts.Days;MessageBox.Show("There are " + daysBetween.ToString() + " days between " + earlierDate.ToShortDateString() + " and " + laterDate.ToShortDateString());

Note: Pay attention to how we create the output string.

Page 28: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Comments

• Line comment: //// my comment

• Block comment: /* …… *//* comment 1

Comment 2…Comment n */

Page 29: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Throwing an Exception

• In the following example, the user may entered invalid data (e.g. null) to the milesText control. In this case, an exception happens (which is commonly said to “throw an exception”).

• The program then jumps to the catch block.• You can use the following to display an exception’s default error message:

catch (Exception ex) { MessageBox.Show(ex.Message); }

try{ double miles; double gallons; double mpg;

miles = double.Parse(milesTextBox.Text); gallons = double.Parse(gallonsTextBox.Text); mpg = miles / gallons; mpgLabel.Text = mpg.ToString();}catch{ MessageBox.Show("Invalid data was entered."):}

Page 30: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Decision Structure• The flowchart is a single-alternative decision

structure• It provides only one alternative path of

execution• In C#, you can use the if statement to write such

structures. A generic format is:

if (expression){Statements;Statements;etc.;}

• The expression is a Boolean expression that can be evaluated as either true or false

Coldoutside

Wear a coat

True

False

Page 31: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Relational Operators

• A relational operator determines whether a specific relationship exists between two values

Operator Meaning Expression Meaning

> Greater than x > y Is x greater than y?

< Less than x < y Is x less than y?

>= Greater than or equal to x >= y Is x greater than or equal to y?

<= Less than or equal to x <= y Is x less than or equal to you?

== Equal to x == y Is x equal to y?

!= Not equal to x != y Is x not equal to you?

Page 32: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

The if-else statement• An if-else statement will execute one block of statement if its

Boolean expression is true or another block if its Boolean expression is false

• It has two parts: an if clause and an else clause• In C#, a generic format looks:

if (expression){ statements;}else{ statements;}

Page 33: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

The if-else-if Statement• You can also create a decision structure that evaluates multiple conditions

to make the final decision using the if-else-if statement• In C#, the generic format is:

if (expression){}else if (expression){}else if (expression){}…else {}

int grade = double.Parse(textBox1.Text);if (grade >=90) { MessageBox.Show("A"); }else if (grade >=80) { MessageBox.Show("B"); }else if (grade >=70) { MessageBox.Show("C");}else if (grade >=60) { MessageBox.Show("D");}else { MessageBox.Show("F");}

Page 34: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Logical Operators• The logical AND operator (&&) and the logical OR operator (||) allow you

to connect multiple Boolean expressions to create a compound expression

• The logical NOT operator (!) reverses the truth of a Boolean expression

Operator Meaning Description

&& AND Both subexpression must be true for the compound expression to be true

|| OR One or both subexpression must be true for the compound expression to be true

! NOT It negates (reverses) the value to its opposite one.

Expression Meaning

x >y && a < b Is x greater than y AND is a less than b?

x == y || x == z Is x equal to y OR is x equal to z?

! (x > y) Is the expression x > y NOT true?

Page 35: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Sample Decision Structures with Logical Operators

• The && operatorif (temperature < 20 && minutes > 12){ MessageBox.Show(“The temperature is in the danger zone.”);}

• The || operatorif (temperature < 20 || temperature > 100){ MessageBox.Show(“The temperature is in the danger zone.”);}

• The ! Operatorif (!(temperature > 100)){ MessageBox.Show(“The is below the maximum temperature.”);}

Page 36: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Boolean (bool) Variables and Flags

• You can store the values true or false in bool variables, which are commonly used as flags

• A flag is a variable that signals when some condition exists in the program– False – indicates the condition does not exist– True – indicates the condition exists

Boolean good;// bool good;if (mydate.Year == 2011) { good = true; }else { good = false; }MessageBox.Show(good.ToString());

Page 37: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Sample switch Statementswitch (month){ case 1: MessageBox.Show(“January”); break;

case 2: MessageBox.Show(“February”); break;

case 3: MessageBox.Show(“March”); break;

default: MessageBox.Show(“Error: Invalid month”); break;}

month

Display “January”

Display “February”

Display “March”

Display “Error: Invalid

month”

Page 38: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Structure of a while Loop• In C#, the generic format of a while loop is:

while (BooleanExpression){ Statements;}

• Example:• while (count < 5) • {• counter = count + 1;• // counter ++;• }• MessageBox.Show(counter.ToString());

Page 39: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

The for Loop

• The for loop is specially designed for situations requiring a counter variable to control the number of times that a loop iterates

• You must specify three actions:– Initialization: a one-time expression that defines the initial value of the

counter– Test: A Boolean expression to be tested. If true, the loop iterates.– Update: increase or decrease the value of the counter

• A generic form is:

for (initializationExpress; testExpression; updateExpression){ }

• The for loop is a pretest loop

Page 40: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Sample Codeint count;for (count = 1; count <= 5; count++){ MessageBox.Show(“Hello”);}

•The initialization expression assign 1 to the count variable•The expression count <=5 is tested. If true, continue to display the message.•The update expression add 1 to the count variable•Start the loop over

// declare count variable in initialization expressionfor (int count = 1; count <= 5; count++){ MessageBox.Show(“Hello”);}

Page 41: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Other Forms of Update Expression• In the update expression, the counter variable is typically incremented by

1. But, this is not a requirement.

//increment by 10for (int count = 0; count <=100; count += 10){ MessageBox.Show(count.ToString());}

• You can decrement the counter variable to make it count backward

//counting backwardfor (int count = 10; count >=0; count--){ MessageBox.Show(count.ToString());}

Page 42: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

The do-while Loop

• The do-while loop is a posttest loop, which means it performs an iteration before testing its Boolean expression.

• In the flowchart, one or more statements are executed before a Boolean expression is

tested• A generic format is:

do{ statement(s);} while (BooleanExpression); Boolean

Expression

Statement(s)

True

False

Page 43: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Programming Interface Controls with C#

Page 44: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Working with Form

• To close a form:– this.Close();

• To choose the startup form:Change the code in Program.cs– Example, to start from form2 instead of form1,

use this code:• Application.Run(new Form2());

Page 45: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Form Closing Eventprivate void Form2_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Cancel = false; } else { e.Cancel = true; } }

Page 46: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

• Modeless form: Other forms can receive input focus while this form remains active.– FormName.Show()

• Modal form: No other form can receive focus while this form remains active.– FormName.ShowDialog()

Page 47: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Multiple FormsTwo forms: Form1, Form2To Open Form2 from Form1:

Standard but troublesome way to open a form: Must create an instance of the form class by using the keyword New to access the form.

Form2 f2 = new Form2 ();

Open Form2 as a Modeless form:

f2.Show ();

Open Form2 as a Modal form:

f2.ShowDialog();

Demo: Problem with the Show method

.

Page 48: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Interactive Input using VB’s InputBox Statement

Add a reference to Microsoft Visual Baisc:1. From the Solution Explorer, right-click the References node, then click Add Reference2. Click Assemblies/Framework and select Microsoft Visual Baisc3. Add this code to the form:

using Microsoft.VisualBasic;

int myint;myint= int.Parse(Interaction.InputBox("enter a number:"));MessageBox.Show(myint.ToString());

Example of using InputBox:

Page 49: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Accumulator

Find the sum of all even numbers between 1 and N.

int N, Sum, Counter = 1;N = int.Parse(Interaction.InputBox("enter an integer:"));Sum = 0;while (Counter <= N) { if (Counter % 2 ==0)

Sum += Counter; ++Counter; }MessageBox.Show(Sum.ToString());

Method 1:

Page 50: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

TextBox Validating EventExample: Testing for digits only

There is no equivalent IsNumeric function in C#. This example uses the Double.Parse method trying to convert the data entered in the box to double. If fail then it is not numeric.

private void textBox1_Validating(object sender, CancelEventArgs e) { try { Double.Parse(textBox1.Text); e.Cancel = false; } catch { e.Cancel = true; MessageBox.Show("Enter digits only"); } }

Page 51: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Working with Radiobuttons, Listbox• Create a form with 2 radiobuttons. When radiobutton1

is selected, populate a listbox with fruit names.; otherwise populate the listbox with vegetable names. Then, dsplay the fruit or vegetable’s name in a textbox when user select an item from the listbox.

Page 52: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

private void radioButton1_CheckedChanged(object sender, EventArgs e) { if (radioButton1.Checked) { listBox1.Items.Clear(); listBox1.Items.Add("Apple"); listBox1.Items.Add("Orange"); listBox1.Items.Add("Banana"); listBox1.Items.Add("Strawberry"); listBox1.Items.Add("Papaya"); } if (radioButton2.Checked) { listBox1.Items.Clear(); listBox1.Items.Add("Spinach"); listBox1.Items.Add("Brocoli"); listBox1.Items.Add("Tomato"); listBox1.Items.Add("Lettuce"); listBox1.Items.Add("Cabbage"); } }

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Text = listBox1.SelectedItem.ToString(); }

Page 53: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Create a Loan Payment Form

Page 54: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Using VB.Net’s PMT Function

• Add a reference to Microsoft Visual Baisc– From the Solution Explorer, right-click the

References node, then click Add Reference– From the .Net tab, select Microsoft Visual

Baisc– Add this code to the form:

• using Microsoft.VisualBasic;

Page 55: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

private void button1_Click(object sender, EventArgs e) { double loan, term, rate, payment; loan = Double.Parse(textBox1.Text); if (radioButton1.Checked) { term = 15; } else { term = 30; } switch (listBox1.SelectedIndex) { case 0: rate=.05; break; case 1: rate=.06; break; case 2: rate = .07; break; case 3: rate = .08; break; case 4: rate = .09; break; default: rate = 0.05; break; } payment = Financial.Pmt(rate / 12, term * 12, -loan); textBox2.Text = payment.ToString(); }

Page 56: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

How to Use VB’s IsNumeric Function

• Add a reference to Microsoft VisualBasic Compatibility namespace.

• Then, add this code to the form:– using Microsoft.VisualBasic;

• Microsoft.VisualBasic.Information class contains the IsNumeric function

if (! Information.IsNumeric(textBox1.Text)) { e.Cancel = true; MessageBox.Show("Enter digits only"); } else { e.Cancel=false; }

Page 57: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

ComboBox• Allows the user to type text directly into the

combo box.• Use the Text property to get entered item:

– ComboBox1.Text– The index for an entered item is –1.

• Search an item in the list: ComboBox1.Items.IndexOf(“search text”)– Found: return the index of the search text.– Not found: return –1.

• How to add an entered item to the list?

Page 58: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

ToolTip

• Add ToolTip to form.

• Use controls’ ToolTipOn property to enter tip.

Page 59: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Timer• Properties:

• Enabled -- must set to True.• Interval

• Tick Event

private void timer1_Tick(object sender, EventArgs e) { textBox1.Text = System.DateTime.Now.ToString(); }

Page 60: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Use a Timer to Close a Form

int counter = 0; private void timer1_Tick(object sender, EventArgs e) { counter+=1;

if (counter > 50) { this.Close(); } }

Page 61: C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows

Using One Event Procedure to Handle Many Events

private void buttonClick(object sender, EventArgs e) { if (sender.ToString().Contains("0")) { Phone = Phone + "0"; } else if (sender.ToString().Contains("1")) { Phone = Phone + "1"; } else { Phone = Phone + "2"; } textBox1.Text = Phone; }