




已阅读5页,还剩42页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic .NET, Second Edition 1 Creating Variables and Named Constants Lesson A Objectives Create a procedure-level and module-level variable Select an appropriate data type for a variable Select an appropriate name for a variable 2 Creating Variables and Named Constants Lesson A Objectives (continued) Assign data to an existing variable Explain the scope and lifetime of a variable Create a named constant 3 Previewing the Completed Application To preview the completed Skate-Away Sales application: Use the Run command on the Start menu to run the Skate (Skate.exe) file contained in the VBNETChap03 folder An order form similar to the one that you created in Chapter 2 appears on the screen 4 Using Variables to Store Information Besides storing data in the properties of controls, a programmer also can store data, temporarily, in memory locations inside the computer The memory locations are called variables, because the contents of the locations can change as the program is running 5 Using Variables to Store Information (continued) One use for a variable is to hold information that is not stored in a control on the user interface You can also store the data contained in a controls property in a variable 6 Selecting a Data Type for a Variable TypeMemory Required TypeMemory Required Byte1 byteShort2 bytes Char2 bytesInteger4 bytes Boolean2 bytesLong8 bytes Decimal16 bytesSingle4 bytes Double8 bytesStringVaries Date8 bytesObject 4 bytes 7 Selecting a Data Type for a Variable (continued) Short, Integer, Long Store whole numbers Single, Double Store floating-point numbers DecimalStores numbers with a decimal point BooleanStores True and False CharStores one Unicode character ByteStores 8-bits of data DateStores date and time information StringStores a sequence of characters 8 Selecting a Name for a Variable The naming convention used in this book: The name indicates only the variables purpose and is entered using lowercase letters Use camel casing: if a variables name contains two or more words, you capitalize the first letter in the second and subsequent words The name assigned to a variable must follow the rules listed in Figure 3-4 9 Selecting a Name for a Variable (continued) Figure 3-4: Rules for variable names along with examples of valid and invalid names 10 Declaring a Variable You use a declaration statement to declare, or create, a variable Syntax: Dim | Private | Static variablename As datatype= initialvalue Examples: Dim hoursWorked As Integer Dim dataOk As Boolean = True Dim name As String, age As Integer 11 Assigning Data to an Existing Variable You use an assignment statement to assign a value to a variable while an application is running Syntax: variablename = value Examples: quantityOrdered = 500 firstName = “Mary” state = Me.uiStateTextBox.Text discountRate = .03 12 Assigning Data to an Existing Variable (continued) A literal constant is an item whose value does not change while the application is running String literal constants are enclosed in quotation marks, but numeric literal constants and variable names are not A literal type character forces a literal constant to assume a data type other than the one its form indicates 13 Assigning Data to an Existing Variable (continued) Figure 3-7: Literal type characters 14 Assigning Data to an Existing Variable (continued) A variable can store only one item of data at any one time When you use an assignment statement to assign another item to the variable, the new data replaces the existing data After data is stored in a variable, you can use the data in calculations 15 The Parse Method Every numeric data type in Visual Basic .NET has a Parse method that can be used to convert a string to that numeric data type Syntax: numericDataType.Parse(string) Example: Dim sales As Decimal sales = Decimal.Parse(Me.uiSalesTextBox.Text) 16 The Convert Class The Convert class contains methods to convert a numeric value to a specified data type Syntax: Convert.method(value) Example: Dim purchase As Double = 500 Dim tax As Decimal tax = Convert.ToDecimal(purchase) * .03D 17 The Convert Class (continued) Figure 3-9: Most commonly used methods contained in the Convert class 18 The Scope and Lifetime of a Variable A variables scope indicates which procedures in an application can use the variable The scope is determined by where the Dim, Public or Private statement is entered When you declare a variable in a procedure, the variable is called a procedure-level variable and is said to have procedure scope 19 The Scope and Lifetime of a Variable (continued) When you declare a variable in the forms Declarations section, it is called a module-level variable and is said to have module scope Block-level variables are declared within specific blocks of code, such as within If.Then.Else statements or For.Next statements 20 The Scope and Lifetime of a Variable (continued) Creating a procedure-level variable Created with the Dim keyword The Dim statement is entered in an objects event procedure Only the procedure in which it is declared can use the variable Removed from memory when the procedure ends 21 The Scope and Lifetime of a Variable (continued) Creating a module-level variable Created with the Private keyword Entered in a forms Declarations section Can be used by any of the procedures in the form Removed from memory when the application ends or the form is destroyed 22 Named Constants A memory location whose contents cannot be changed while the program is running You create a named constant using the Const statement Syntax: Const constantname As datatype = expression Example: Const PI As Double = 3.141593 23 Option Explicit and Option Strict Visual Basic .NET provides a way to prevent you from using undeclared variables in your code Enter the statement Option Explicit On in the General Declarations section of the Code Editor window 24 Option Explicit and Option Strict (continued) To eliminate the problems that occur as a result of implicit type conversions Enter the Option Strict On statement in the General Declarations section of the Code Editor window 25 Option Explicit and Option Strict (continued) Type conversion rules used when the Option Strict On statement is used: Strings will not be implicitly converted to numbers, and numbers will not be implicitly converted to strings Lower-ranking data types will be implicitly promoted to higher-ranking types Higher-ranking data types will not be implicitly demoted to lower-ranking data types; rather, a syntax error will occur 26 Modifying the Skate-Away Sales Application Lesson B Objectives Include a procedure-level and module-level variable in an application Concatenate strings Get user input using the InputBox function Include the ControlChars.NewLine constant in code Designate the default button for a form 27 Storing Information Using Variables You need to revise the Skate-Away Sales applications TOE chart and the pseudocode for the Calculate Order button The uiCalcButton controls Click event procedure now has two more tasks to perform: It must calculate the sales tax It must display the message, sales tax, and salespersons name in the uiMessageLabel control 28 Storing Information Using Variables (continued) Two additional objects (OrderForm and uiMessageLabel) are included in the revised TOE chart The OrderForms Load event procedure is responsible for getting the salespersons name when the application is started The uiMessageLabel control will display the message, sales tax, and salespersons name 29 Storing Information Using Variables (continued) As the revised TOE chart indicates, you need to: Change the code in the uiCalcButtons Click event procedure Code the forms Load event procedure 30 Modifying the Calculate Order Buttons Code You will first remove the existing code from the Calculate Order buttons Click event procedure You then will recode the procedure using variables in the equations Figure 3-18 shows the revised pseudocode for the Calculate Order buttons Click event procedure (changes made to the original pseudocode are shaded in the figure) 31 Modifying the Calculate Order Buttons Code (continued) Figure 3-18: Revised pseudocode for the Calculate Order buttons Click event procedure 32 Concatenating Strings Connecting strings together is called concatenating Use the concatenation operator, which is the ampersand (&), to concatenate strings in Visual Basic .NET When concatenating strings, be sure to include a space before and after the concatenation operator 33 Concatenating Strings (continued) ExampleResult firstName & lastNameSueChen firstName & “ “ & lastNameSue Chen lastName & “, “ & firstNameChen, Sue “She is “ & Convert.ToString(age) & “!” She is 21! “She is “ & age & “!”She is 21! 34 The InputBox Function The InputBox function displays one of Visual Basic .NETs predefined dialog boxes Syntax: InputBox(prompt, title, defaultResponse) Use sentence capitalization for the prompt, and book title capitalization for the title Has limitations: cant control appearance and allows user to enter only one piece of data 35 The InputBox Function (continued) Figure 3-29: Example of a dialog box created by the InputBox function 36 The NewLine Character The NewLine character, which is Chr(13) & Chr(10), instructs the computer to issue a carriage return followed by a line feed The ControlChars.NewLine constant advances the insertion point to the next line on the screen The ControlChars.NewLine constant is an intrinsic constant, which is a named constant that is built into Visual Basic .NET 37 Designating a Default Button Can be selected by pressing the Enter key even when the button does not have the focus Set the forms AcceptButton property to the desired button If used, it is typically the first button If a buttons action is destructive and irreversible, then it should not be the default button 38 Modifying the Skate-Away Sales Applications Code Lesson C Objectives Include a static variable in code Code the TextChanged event procedure Create a procedure that handles more than one event 39 Modifying the Code in the Load and uiCalcButton Click Procedures Mr. Cousard would like to have the order form ask for the salespersons name each time an order is calculated Before making modifications, you should review the applications documentation and revise the necessary documents Figure 3-44 shows the revised pseudocode for the Calculate Order buttons Click event procedure 40 Modifying the Code in the Load and uiCalcButton Click Procedures (continued) Figure 3-44: Revised pseudocode for the Calculate Order button 41 Static Variables A static variable is a local variable that retains its value when the procedure in which it is declared ends Syntax: Static variablename As datatype = initialvalue Removed from memory when application ends or form is removed from memory 42 Coding the TextChanged Event Procedure A controls TextChanged event occurs when the contents of a controls Text property change This can happen as a result of either the user entering data into the control, or the applications code assigning data to the controls Text property 43 Associating a Procedure with Different Objects or Events The keyword Handles appears in a procedure header and indicates the object and event associated with the procedure
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 【语文】小学二年级上学期期末模拟模拟试题
- (完整版)数学初一分班测试模拟试卷经典答案
- 2023年人教版小学四4年级下册数学期末解答综合复习(含答案)经典
- 2025年水务行业化学检验员职业技能竞赛理论考试题库含答案
- 2025预防艾梅乙母婴传播项目培训测试试卷附答案
- 司机营销方案
- 2025年院前急救信息系统项目申请报告
- 2025年杀菌奶项目立项申请报告模板
- 山东省2024年春季高考语文试卷试题真题及答案
- 法律多元主义与环境保护-洞察及研究
- 2024年高级执法资格考试题及解析
- 新学期新起点励志奋斗青春初三毕业班开学第一课主题班会课件
- 分包单位与班组签订合同
- 盐酸右美托咪定鼻喷雾剂-临床用药解读
- 危险货物装载与卸载操作规程
- 《映山红》PPT课件(安徽省市级优课)-五年级音乐课件
- 林则徐课件完整版
- 投资学英文版课件Ch 3 Securities markets
- 氟喹诺酮类药物残留的检测课件
- 2021Z世代职场现状与趋势调研报告
- 全国编辑记者资格证考试复习资料
评论
0/150
提交评论