610 likes | 621 Views
Learn the basics of C# programming using Visual Studio 2013 with a step-by-step demonstration. Understand event-driven programming, controls, properties, and procedures. Discover how to create GUI elements, set properties, and write event procedures. Get hands-on experience with variable declaration, input/output of numeric values, and explicit conversion.
E N D
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 Show Full Name .Control properties .Event: Click, MouseMove, FormLoad, etc. .Event procedures FullName: textBox3.Text textBox3.Text = textBox1.Text + " " + textBox2.Text; Demo: Text alignment (TextBox3.TextAlign=HorizontalAlign.Right) TextBox3.BackColor=Color.Aqua;
Demo Num1 Num2 Compute Sum .Control properties .Event: Click, MouseMove, FormLoad, 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 “ + 25.75);
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 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);
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 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
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 • 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."): }
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 Cold outside True Wear a coat False
Relational Operators • A relational operatordetermines whether a specific relationship exists between two values
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
Sample Decision Structures with Logical Operators • The && operator if (temperature < 20 && minutes > 12) { MessageBox.Show(“The temperature is in the danger zone.”); } • The || operator if (temperature < 20 || 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); Statement(s) Boolean Expression True False
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; Example of using InputBox: int myint; myint= int.Parse(Interaction.InputBox("enter a number:")); MessageBox.Show(myint.ToString());
Accumulator Find the sum of all even numbers between 1 and N. Method 1: 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());
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"); } }