Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 C# Introduction ISYS 512

2 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

3 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

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

5 Common Controls TextBox Label Button CheckBox RadioButton ListBox ComboBox PictureBox

6 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.

7 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.

8 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.

9 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

10 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.

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

12 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

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

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

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

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

17 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

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

19 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.

20 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.

21 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.

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

23 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”)12.300 “F” or “f”Fixed-point scientific format123456.0ToString("f2")123456.00 “E” or “e”Exponential scientific format123456.0ToString("e3")1.235e+005 “C” or “c”Currency format-1234567.8ToString("C")($1,234,567.80) “P” or “p”Percentage format.234ToString("P")23.40%

24 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

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

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

27 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.

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

29 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."): }

30 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

31 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?

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

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

34 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?

35 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.”); }

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

37 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”

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

39 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

40 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”); }

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

42 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

43 Programming Interface Controls with C#

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

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

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

47 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.

48 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 :

49 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:

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

51 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.

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

53 Create a Loan Payment Form

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

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

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

57 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?

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

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

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

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


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

Similar presentations


Ads by Google