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

Slides:



Advertisements
Similar presentations
.NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically. –Programming in.
Advertisements

Programming Interface Controls with VB.Net. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option.
VB.Net Introduction. .NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Processing Data.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Making Decisions.
C# Introduction ISYS 512. Major Differences Between VB Project and C# Project The execution starts from the Main method which is found in the Program.cs.
VB.Net Introduction. .NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically.
VB.Net Introduction. Visual Studio 2010 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# or VB –Windows.
C# Introduction ISYS 350. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows.
Programming Interface Controls with VB.Net. User Interface Controls Form MessageBox, InputBox Common Controls: –Button, TextBox, MaskedTextBox, List Box,
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
VB.Net Introduction. What is programming? Writing computer programs means writing instructions in a logical sequence, that will make the computer follow.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Loops ISYS 350. A Box of Chocolate Repeat this process until box is empty: – Take one chocolate from the box – Eat the chocolate – Box has more chocolate?
C# Introduction ISYS 350. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows.
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
Decision Structure - 2 ISYS 350. Complex Condition with Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Expression and Decision Structure ISYS 350. Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators.
Decision Structure - 2 ISYS 350. Complex Condition with Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to.
Loops ISYS 350. Compute the sum of a list of numbers: Example: 5, 2, 10, 8, 4 Process: Sum= 0 Get a number from the list Sum = Sum + the number Repeat.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
C# Introduction ISYS 350. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows.
Loops ISYS 350. Two Types of Loops while loop for loop.
VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
Loops ISYS 350. Two Types of Loops while loop for loop.
Loops ISYS 350. Two Types of Loops while loop for loop.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
C# Introduction ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure ISYS 350.
Decision Structure - 1 ISYS 350.
Loops ISYS 350.
C# Introduction ISYS 350.
C# Introduction ISYS 350.
Loops ISYS 350.
C# Introduction ISYS 350.
Programming Interface Controls
Programming Interface Controls
Decision Structure - 2 ISYS 350.
C# Introduction ISYS 350.
Decision Structure - 1 ISYS 350.
C# Introduction ISYS 350.
Lesson 04 Control Structures I : Decision Making
C# Introduction ISYS 350.
Work with Data and Decision Structure
Loops ISYS 350.
C# Introduction ISYS 350.
Decision Structure - 2 ISYS 350.
Loops ISYS 350.
Decision Structures ISYS 350.
Decision Structure - 2 ISYS 350.
CIS 16 Application Development Programming with Visual Basic
Decision Structure - 2 ISYS 350.
C# Introduction ISYS 350.
Loops ISYS 350.
VB.Net Introduction.
Decision Structure - 1 ISYS 350.
Loops ISYS 350.
Decision Structure - 2 ISYS 350.
Loops ISYS 350.
Loops ISYS 350.
Decision Structure - 1 ISYS 350.
Loops ISYS 350.
Programming Interface Controls
C# Introduction ISYS 350.
Presentation transcript:

C# Introduction ISYS 512

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

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

Form Properties: –Name, FormBorderStyle, Text, BackColor, BackImage, Opacity Events: –Load, FormClosing, FormClosed –GotFocus, LostFocus –MouseHover, Click, DoubleCLick

Common Controls TextBox Label Button CheckBox RadioButton ListBox ComboBox PictureBox

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.

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.

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.

Demo FirstName LastName.Control properties.Event: Click, MouseMove, Form Load, etc..Event procedures FullName: textBox3.Text textBox3.Text = textBox1.Text + " " + textBox2.Text; Demo: Text alignment (TextBox3.TextAlign=HorizontalAlign.Right) TextBox3.BackColor=Color.Aqua; Show Full Name

Demo Num1 Num2 Compute Sum.Control properties.Event: Click, MouseMove, Form Load, etc..Event procedures Sum: textBox3.Text = (double.Parse(textBox1.Text) + double.Parse(textBox2.Text)).ToString(); In-Class lab: Show the product of Num1 and Num2.

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

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

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 “;”

string DataType string Variables: Examples: string empName; string firstName, lastAddress, fullName; String concatenation: + Examples: fullName = firstName + lastName; MessageBox.Show(“Total is “ );

Numeric Data Types int, double Examples: double mydouble=12.7, rate=0.07; int Counter = 0;

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

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

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*/

Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators OperatorName of the operatorDescription +AdditionAdds two numbers -SubtractionSubtracts one number from another *MultiplicationMultiplies one number by another /DivisionDivides one number by another and gives the quotient %ModulusDivides one number by another and gives the remainder Other calculations: Use Math class’s methods.

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.

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.

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

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 DescriptionNumberToString()Result “N” or “n”Number format12.3ToString(“n3”) “F” or “f”Fixed-point scientific format ToString("f2") “E” or “e”Exponential scientific format ToString("e3")1.235e+005 “C” or “c”Currency format ToString("C")($1,234,567.80) “P” or “p”Percentage format.234ToString("P")23.40%

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

DateTime Example DateTime myDate; myDate = DateTime.Parse(textBox1.Text); MessageBox.Show(myDate.ToLongDateString()); MessageBox.Show(DateTime.MinValue.ToShortDateString()); MessageBox.Show(DateTime.MaxValue.ToShortDateString());

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;

Code Example DateTime 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.

Comments Line comment: // // my comment Block comment: /* …… */ /* comment 1 Comment 2 … Comment n */

Throwing an Exception I n 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."): }

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; etc.; } The expression is a Boolean expression that can be evaluated as either true or false Cold outside Wear a coat True False

Relational Operators A relational operator determines whether a specific relationship exists between two values OperatorMeaningExpressionMeaning >Greater thanx > yIs x greater than y? <Less thanx < yIs x less than y? >=Greater than or equal tox >= yIs x greater than or equal to y? <=Less than or equal tox <= yIs x less than or equal to you? ==Equal tox == yIs x equal to y? !=Not equal tox != yIs x not equal to you?

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; }

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"); }

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 OperatorMeaningDescription &&ANDBoth subexpression must be true for the compound expression to be true ||OROne or both subexpression must be true for the compound expression to be true !NOTIt negates (reverses) the value to its opposite one. ExpressionMeaning x >y && a < bIs x greater than y AND is a less than b? x == y || x == zIs x equal to y OR is x equal to z? ! (x > y)Is the expression x > y NOT true?

Sample Decision Structures with Logical Operators The && operator if (temperature 12) { MessageBox.Show(“The temperature is in the danger zone.”); } The || operator if (temperature 100) { MessageBox.Show(“The temperature is in the danger zone.”); } The ! Operator if (!(temperature > 100)) { MessageBox.Show(“The is below the maximum temperature.”); }

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

Sample switch Statement switch (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”

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

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

Sample Code int 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 expression for (int count = 1; count <= 5; count++) { MessageBox.Show(“Hello”); }

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 10 for (int count = 0; count <=100; count += 10) { MessageBox.Show(count.ToString()); } You can decrement the counter variable to make it count backward //counting backward for (int count = 10; count >=0; count--) { MessageBox.Show(count.ToString()); }

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

Programming Interface Controls with C#

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

Form Closing Event private 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; }

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

Multiple Forms Two forms: Form1, Form2 To 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.

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 Reference 2. Click Assemblies/Framework and select Microsoft Visual Baisc 3. 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 :

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:

TextBox Validating Event Example: 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"); }

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.

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

Create a Loan Payment Form

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;

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

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; }

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?

ToolTip Add ToolTip to form. Use controls’ ToolTipOn property to enter tip.

Timer Properties: Enabled -- must set to True. Interval Tick Event private void timer1_Tick(object sender, EventArgs e) { textBox1.Text = System.DateTime.Now.ToString(); }

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

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; }