Chapter 1 objectives
Describe the process of visual program design and development Explain the term object-oriented programming
Object Oriented Programming (OOP) — C#, Java, Visual Basic User controls the sequence
User actions cause events to occur which trigger methods Explain the concepts of classes, objects, properties, methods, and events List and describe the three steps for writing a C# program
Three steps(planning)
Design the user interface
Plan the properties
Plan the C# code
Three steps(planning)
Define user interface
Set the properties
Write the code
Describe the various files that make up a C# project
.sln **Form.cs Program.cs **Form.resx **Form.Designer.cs Identify the elements in the Visual Studio environment
Form designer
Editor for entering and modifying C# code
Compiler
Debugger
Object Browser
Help
Define design time, run time, and debug time
Design Time
Design user interface (forms)
Write code
Run Time
Testing project
Running project
Debug Time
Run-time errors
Pause program execution
Write, run, save, and modify your first C# program
Identify syntax errors, run-time errors, and logic errors
Syntax errors
Breaking the rules of the language
Run-time errors or exceptions
Program halts due to statements that cannot execute
Logic errors
Program runs but produces incorrect results
Look up C# topics in Help
Forms controls Objects Properties Methods Events Classes
C# Versions Express Edition, Standard Edition, Professional Edition, Team System
Toolbox MainDocument Window Solution Explorer Property Window
Snap Line基准线
Comment statements 注释 // /**/
braces { }
underscore (_)
semicolon (;)
parentheses 括号
Renaming a Control
Change the name of the control in the design window
Switch to Editor window 编辑窗口
Right-click name of event-handling method
Select Refractor/Rename
Enter new name in Rename dialog box
Click Apply in Preview Changes dialog box
Chapter 2 Objectives
Use text boxes, masked text boxes, rich text boxes, group boxes, check boxes, radio buttons, and picture boxes effectively
Set the BorderStyle property to make controls appear flat or three-dimensional
Select multiple controls and move, align, and set common properties for them
Make your projects easy for the user to understand and operate
Define access keys
Set Accept and Cancel buttons
Control the tab sequence, resetting the focus during program execution
Use ToolTips
Clear the contents of text boxes and labels
Make a control visible or invisible at run time by setting its Visible property
Disable and enable controls at design time and run time
Change text color during program execution
Concatenate (join) strings of text
Download the Line and Shape controls, add them to the toolbox, and use the controls on forms
TextBox
Text
TextAlign(left/right/center):文本对齐方式
WordWrap(true/false):允许长单词换行
Multiline(true/false):是否可以显示一行以上数据
MaskedTextBox(masked:隐蔽的):输入格式化的数据
Mask
RichTextBox:输入多行文本
DetectUrls:将Url自动转化为网址
LoadFile:load .rtf file
GroupBox:
Enabled
Text
CheckedBox:
Checked
Event:CheckedChanged
RadioButton:
Checked
PictureBox:
Image
SizeMode(Normal/StretchImage/Zoom/AutoSize/CenterImage):是否适应画框大小
BoarderStyle(None/FixedSingle/Fixed3D)
Keyboard Access Keys(Hot Keys):&(Alt+underlined word)
AcceptButton:Enter
CancelButton:Esc
Tab Order:
TabStop(true/false)
TabIndex(0——)
ToolTip on ToolTip1(对每个控件加标记)
清空:1、“”2、string.empty 3.(textBox)TextBox.clear();
TextBox.focus();
Environment.NewLine
Enabled visible ForeColor BackColor
Chapter 3 Objectives
Declare variables and constants
Select the appropriate scope for a variable
Convert text input to numeric values
Perform calculations using variables and constants
Convert between numeric data types using implicit and explicit 强制 conversions Round decimal values using the decimal.Round method
Format values for output using the ToString method
Use try/catch blocks for error handling
Display message boxes with error messages
Accumulate sums and generate counts
Constants
const decimal DISCOUNT_RATE_Decimal=.15M;
decimal M
Byte bool DateTime decimal
Decimal:business application
Float/double:scientific application
Intrinsic constant
Scope and Lifetime of Variables
Namespace
Also referred to as global
Class-level
Local 在方法中使用
Block 在{ }中使用
All constants should be declared at class level
文本转化为数字:
quantityInteger=int.parse(quantityTextBox.text);
数字转化为文本:
quantityTextBox=quantityInteger.toString();
Format data:
C:currency;N:number;N3:三位小数;F ;D ;
Hierarchy Increment Decrement Prefix notation Postfix notation 求幂:Math.pow(x,y);
Implicit conversion:
C# has no implicit conversions to convert from decimal
Explicit conversion(casting):
numberDecimal = (decimal) numberFloat;//可以!!!
或:numberDecimal=Convert.ToDecimal(numberFloat);
Rounding numbers
resultDecimal = decimal.Round(amountDecimal, 2); //if 5, to even number
Output:TextBox
Handling exception:
Try...catch...finally...
FormatException
InvalidCastException
ArithmeticException
System.IO.EndofStreamException
OutOfMemoryException
Exception
MessageBox.Show(TextMessage,TitleBarText,MessageBoxButtons,MessageBoxIcon);
TextBox.SelectAll();
TextBox.Focus();
Test each Parse method(using try-catch block)
Chapter 4 objectives
Use if statements to control the flow of logic
Test the Checked property of radio buttons and check boxes using if statements
Perform validation on numeric fields using if statements
Use a switch structure for multiple decisions
Use one event handler to respond to the events for multiple controls
Call an event handler from other methods
Create message boxes(enhancing) with multiple buttons and choose alternate actions based on the user response
Debug projects using breakpoints, stepping program execution, and displaying intermediate results
Comparing strings
Compare strings with equal to (==) and not equal to (!=) operators
aString.CompareTo(bString)
Comparing Uppercase and Lowercase Characters
TextString.ToUpper(); TextString.ToLower();
Priority: ! && ||
Checking the State of a Radio Button Group: if...else if...
Checking the State of Multiple Check Boxes: if...if...
escape sequence(转义字符)
Enhancing MessageBox:
DialogResult whichButtonDialogResult;
whichButtonDialogResult=MessageBox.Show(“content”,”title”,MessageBoxButtons.OKCancel,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button1,MessageBoxOptions.RightAlign) If(whichButtonDialogResult==DialogResult.OK)
{
}
Performing Multiple Validations
if (nameTextBox.Text != "")
{
try
{
unitsDecimal = decimal.Parse(unitsTextBox.Text);
if (freshmanRadioButton.Checked || sophomoreRadioButton.Checked || juniorRadioButton.Checked || seniorRadioButton.Checked) {
// Data valid - - Do calculations or processing here.
}
else
{
MessageBox.Show(“Please select grade level.”, MessageBoxButtons.OK);
}
}
catch(FormatException)
{
//Display error message
}
}
Sharing an event handler Data Entry Error”, “
Duplicate
Calling Event Handlers
“Call” the method from another method by naming the method
Chapter 5 Objectives
Create menus and submenus for program control
Display and use the Windows common dialog boxes(ColorDialog,FontDialog) Create context menus for controls and the form
Write reusable code in methods and call the methods from other locations
Menu
ToolStripMenuItems
ToolStripComboBoxes
ToolStripSeparators
ToolStripTextBoxes
Properties:enabled,checked,showShortcutKey
Modal versus Modeless Windows
A dialog box is said to be modal
The box stays on top of the application and must be responded to
Use the ShowDialog method
A window that does not require response is said to be modeless
Use the Show method
No other program code can execute until the user responds to, hides, or closes a modal form
Modeless—Close destroys the form instance and removes it from memory
Modal—Close only hides the form instance
If the same instance is displayed again, any data from the previous ShowDialog will still be there
colorDialog/fontDialog
Set initial values
colorDialog1.Color = textBox1.BackColor;
colorDialog1.ShowDialog();
textBox1.BackColor = colorDialog1.Color;
If the user presses Cancel, property setting for the objects will remain unchanged(否则有可能会自行改变)
Context menus
A context menu does not have a top-level menu, only menu items(没有最顶级菜单,只有具 体的菜单项)
为特定的项添加contextMenuStrip(e.g. Form, label,button...)
Writing General Methods
An example
private decimal sumPrice(decimal numberDecimal)
Ref parameter(调用方法中赋初值)
直接改变调用方法中的。。。(strongly against)
Out parameter(调用方法中不用赋初值)
An address is sent to the method rather than the value
Basing a New Project on an Existing Project
Chapter 6 Objectives
Include multiple forms in an application
Use a template 模板 to create an About box form
Use the Show, ShowDialog, and Hide methods to display and hide forms
Understand the various form events and select the best method for your code
Declare variables with the correct scope and access level for multiform 多种projects
Create new properties of a form and pass data values from one form to another
Create and display a splash screen
Run your project outside of the IDE
Display AboutBox
AboutBox1 aboutbox = new AboutBox1();
aboutbox.ShowDialog();
Responding to Form Events
FormName.Load
Occurs only the first time a form is loaded into memory
FormName.Activated
Occurs after the Load event, just as control is passed to a form
Occurs each time the form is shown
A good location to place initializing steps or set the focus in a particular place on the form
Deactivate – Occurs when the form is no longer the active form
When a user clicks another window or the form is about to be hidden or closed FormClosing – Occurs as the form is about to close
FormClosed – Occurs after the form is closed
Variables and Constants in Multiform Projects
Private variables and constants within a form (or other class) cannot be seen by code in other classes
Private is the default access level
To declare variables as Public makes them available to all other classes
Public variables present security problems and violate the principles of object oriented programming (OOP)
The correct approach for passing variables from one form object to another is to set up properties of the form’s class
Use a property method to pass values from one form to another
Creating Properties in a Class
Set...get...
Private int numberInteger;
Public int accessNumberInteger
{
Get
{
Return numberInteger;
}
Set
{
numberInteger=value;
}
}
Uses the value keyword to refer to the incoming value for the property
Passing Summary Values among Forms Get set
private static decimal totalDecimal;
public static decimal total
{
set
{
totalDecimal = value;
}
get
{
return totalDecimal;
}
Form1.total += passDecimal;
SplashForm
Text 空
ControlBox:true
StartPosition:CenterScreen
TopMost:true
加一个Timer计时
Enabled=true;
Interval=5000;//millisecond
Program.cs splashForm先新建,再showDialog();
Bin/Debug 有可以直接运行的.exe文件
Chapter07 objectives
Create and use list boxes and combo boxes
Differentiate among the available types of combo boxes
Enter items into list boxes using the Items collection in the Properties window
Add and remove items in a list at run time
Determine which item in a list is selected
Use the Items.Count property to determine the number of items in a list
Display a selected item from a list
Use do, while, and for loops to execute a series of statements
Skip to the next iteration 反复of a loop by using the continue statement
Send information to the printer or the Print Preview window using the PrintDocument class
List box combo box
ComboBox
DropDownStyle(simple,dropDownList,DropDown)
Items(collection)
Sorted(true/false)
comboBox1.items.add(comboBox1.text);
comboBox1.items.insert(1,comboBox1.text);
comboBox1.selectedIndex;
comboBox1.Items.Count;
Items.Count is always one more than the highest possible SelectedIndex comboBox1.Items[1]=””;
comboBox1.items.RemoveAt[0];
comboBox1.items.Remove(“Liu”);
comboBox1.items.clear();
Place a break statement to exit a for, while or do/while loop
Continue
printDocument1.print();
或 printPreviewDialog.Document=printDocument1;
printPreviewDialog.ShowDialog();
(printFont.GetHeight)
e.Graphics.DrawString(“Myname”,newFont(“Arial”,36),Brushes.Black,e.MarginBounds.Left,e.MarginBounds.Top);
SizeF fontSize=e.Graphics.MeasureString(myString,newFont);
fontSize.Width;
看书317页e.HasMorePages(true/false)
Chapter 8 objectives
Establish an array and refer to individual elements in the array with subscripts
Use a foreach loop to traverse遍历 the elements of an array
Create a structure for multiple fields of related data
Accumulate totals using arrays
Distinguish between direct access and indirect access of a table
Write a table lookup for matching an array element
Combine the advantages of list box controls with arrays
Store and look up data in multidimensional arrays
Subscript
Foreach(read only)
int indexInteger = 0;
decimal[] allItemsDecimal = new decimal[] {1,2,3,4};
foreach (decimal oneItemDecimal in allItemsDecimal) // Display all elements in the array.
{
richTextBox1.Text += indexInteger++ + "\t" + oneItemDecimal.ToString() + "\n";
}
struct
struct Employee
{
public string lastNameString;
public string firstNameString;
public string SSNString;
public string streetString;
public string stateString;
public string ZIPString;
public DateTime hireDateTime;
public int payCodeInteger;
}
Attention
An array can be included in a structure, but you cannot specify the number of elements in the struct declaration
Public struct SalesDetail //Class-level declarations.
{
public decimal[] saleDecimal;
}
SalesDetail housewaresSalesDetail;
housewaresSalesDetail.saleDecimal = new decimal[7];
二维数组
string[,] nameString = new string[3, 4];
string[,] nameString = new string[,] = { {"James", "Mary", "Sammie", "Sean"},
{"Tom", "Lee", "Leon", "Larry"}, {"Maria", "Margaret", "Jill", "John"} };
Chapter 11 Objectives
Using System.IO;
int indexInteger=0;
String[] phoneData=new String[10];
save
File.WriteAllLines(“TextFile.txt”,true);
add
phoneData[indexInteger++]=nameText.text;
phoneData[indexInteger++]=numberText.text;
nameText.clear();
numberText.clear();
nameText.focus();
String[] phoneData=File.ReadAllLines(“TextFile.txt”);
String phoneData=File.ReadAllText(“TextFile.txt”);
String[] fileString=phoneData.Split(‘\n’);
WriteAllLines(FileName,ArrayToWrite)
WriteAllText(FileName,StringToWrite)
AppendAllText(FileName,StringToWrite)
Using System.IO;
StreamWriter phoneStreamWriter=new StreamWriter(“Phone.txt”);
Save
phoneStreamWriter.writeLine(phoneTextBox.text);
phoneTextBox.clear();
phoneTextBox.focus();
Exit
phoneStreamWriter.close();
This.close();
StreamReader phoneStreamReader = new StreamReader("Phone.txt");
StreamReader nameStreamReader = new StreamReader("Name.txt");
if (phoneStreamReader.Peek() != -1)
{
textBox1.Text = phoneStreamReader.ReadLine();
textBox2.Text = nameStreamReader.ReadLine();
}
Chapter 9 Objectives
Explain the functions of the server and the client in Web programming
Create a Web Form and run it in a browser
Describe the differences among the various types of Web controls and the relationship of Web controls to controls used on Windows forms
Understand the event structure required for Web programs
Design a Web Form using tables
Create multiple pages in a Web application
Navigate 操纵using the HyperLink 超链接 control and the Server object
Validate Web input using the validator controls
Use state management to preserve values in variables
Web applications require a server and a client
Server sends the Web Pages to the client
Client displays the Web Pages in a browser
Browsers display pages written in a markup language such as HTML or XHTML
Write object-oriented, event-driven Web applications using C# and ASP.NET
Sending state information to the server as part of the page's address, called the uniform resource locator (URL)
A new Web site automatically contains one Web page, Default.aspx
In Design view, client-side HTML controls and ASP server controls are different
Always remove debugging support before deploying an application
HyperLink control
NavigateUrl
Validator Controls
controlToValidate
ErrorMessage
Web pages hold static data
EnableViewState property(是否保存其他页面状态)
EnableViewState property holds the value during postback
Retaining the Values of Variables
EnableViewState property holds the value during postback
Set up a control with its Visible property set to false or use the HiddenField control Test for IsPostBack == false to perform initialization tasks
Test for IsPostBack == true to perform tasks only on postback
Pass Data Between pages
Use the Session variable technique to pass data between pages
One instance of the Session object exists for each user of an application