visual basic 2012 大学教程(第8章)

合集下载

程序设计基础-Visual Basic教程第8章 过程

程序设计基础-Visual Basic教程第8章 过程
VB的程序代码部分是由若干被称为“过程”的代码行 以及向系统提供某些信息的说明组成。其中有针对于 某个对象的事件过程,也有用户自定义过程,而这些 过程及说明又被组织在不同的“模块”文件之中
应用程序(.vbp文件)
若干窗体模块(.frm文件) 若干标准模块(.bas文件) 若干类模块(.cls文件)
若干事件过程(Sub) 自定义子程序过程(Sub) 自定义函数过程(Function)
第8章 过程
本章的学习重点和难点
VB程序代码的组织 弄清楚过程调用的程序流程 过程的编写,参数的设置(包含数量、类型、顺序 的要求)、参数的传递方式的选用 递归过程的编写、递归过程的调用和回溯过程的理 解 变量的作用域问题(局部(过程级、模块级)、全局、 静态变量)、作用域不同的变量的同名问题
8.1 VB程序代码的结构化组织
8.1 VB程序代码的结构化组织
8.1.2 过程
自定义过程
结构化编程的原则:“分而治之”,逐步求精的方
法,程序设计模块化 一个应用程序可以具有若干个窗体,每个窗体又可 能拥有相同或不相同的对象,但是这些不同窗体中 的对象却有可能引发相同的操作或需要进行某些 共同的处理,也就是说,一个应用中的多个窗体可 以共享一些代码,或者一个窗体内不同的事件过程 可共享一些代码
8.1.2 过程
事件过程
尽管窗体有各自的名称,但窗体事件过程名由
下划线和事件名构成窗件事件过程名
“Form”、下划线和事件名结合而成;如果使 用多文档界面(MDI)窗体,则由“MDIForm”、
控件事件过程名由控件名、下划线和事件名组成。
组成控件事件过程名的控件名必须与窗体中某个控 件相匹配,否则VB将认为它是一个自定义过程
8.1 VB程序代码的结构化组织

精品课件-Visual Basic程序设计项目化案例教程-第8章

精品课件-Visual Basic程序设计项目化案例教程-第8章

第8章 菜单与工具栏设计 图8-6
第8章 菜单与工具栏设计
“插入按钮”:单击它可以在工具栏上插入Button对象。 “删除按钮”:单击它可以删除当前Button对象。 “索引”文本框:该文本框中的数字表示每个按钮的数字 编号,在ButtonClick事件中引用。 “关键字”文本框:该文本框中的内容表示每个按钮的标 识名,在ButtonClick事件中引用。 “图像”文本框:选定ImageList对象中的图像,可以用 图像的Key或Index值。 “样式”下拉列表框:指定按钮样式,共有5种,含义见 表8-3。
第8章 菜单与工具栏设计
三、操作步骤 1.创建程序界面 (1) 启动Visual Basic 6.0,新建一个“标准 EXE”工程。 (2) 在窗体上添加一个文本框控件,两个组合框控件。 (3) 打开菜单编辑器窗口设计菜单,菜单的各项设置如表 8-4所示。
第8章 菜单与工具栏设计
菜单项 主菜单项 1 子菜单项 1-1 子菜单项 1-2 子菜单项 1-3 主菜单项 2 子菜单项 2-1 子菜单项 2-2 子菜单项 2-3
第8章 菜单与工具栏设计
表8-3 按钮样式及含义

常数
按钮
含义
0
TbrDefault
普通按钮
按钮按下后恢复原态
1
TbrCheck
开关按钮
按钮按下后将保持按下状态
2
TbrButtonGroup 编组按钮
一组按钮同时只能一种有效
3
TbrSepatator 分隔按钮
左右的按钮分隔其他按钮
4
TbrPlaceholder 占位按钮
第8章 菜单与工具栏设计
(4) :单击该按钮可将菜单列表中选定的菜单标题或

Visual Basic程序设计教程第八章

Visual Basic程序设计教程第八章
9
• (8)Exit Function:在函数过程体执行 过程中,若需要中途退出函数过程,则 可以采用Exit Function语句强行结束函 数过程的调用。Exit Function语句往往 与条件语句配合使用,用于产生有条件 的中途退出的效果。
10
8.2.2 Function过程的调用
• Function过程的调用比较简单,它可以 像使用VB的内部函数一样来调用 Function过程。实际上,Function过程就 是一个函数,它与内部函数并无什么区 别,只不过内部函数由系统提供,而 Function过程是由用户根据需要由自己 定义的。
4
8.2.1 函数过程的定义
• 1.Function过程定义的格式 • [Static]|[Private]|[Public]Function <过程 名>[(参数列表)][As 类型] • 过程体(函数体) • [语句组] [过程名=表达式] • [Exit Function] • [语句组] • End Function
19Biblioteka • (4)<过程名>:命名规则与变量名的 命名规则相同。一个程序中,过程名应 具有唯一性。过程名在此仅仅表示本 Sub过程的名字而已(它不像函数过程 名),不与数据发生联系,因此在过程 头部,不能定义Sub过程名的数据类型 ,在Sub过程体中,也不能对Sub过程名 进行赋值。
17
• 2.说明 • (1)通用过程通常完成一个特定的任务, 它不与任何特定的事件相联系,只能由其 他的过程来调用,它还可以存储在窗体模 块或标准模块中。 • (2)可以将子过程放入标准模块、类模块 和窗体模块中。缺省规定所有模块中的子 过程为Public(公用的),这意味着在应用 程序中可以随处调用它们;若选用Private( 局部),则只有该过程所在模块中的程序 18 才能调用该过程。

Visual Basic 程序设计教程第8章

Visual  Basic 程序设计教程第8章

3.滚动条
属性:
(1)Max属性 (2)Min属性 (3)Value属性
事件:
(1)Scroll事件 (2)Change事件
方法:
二.时钟
①属性:
Interval属性、Enabled属性 事件: 方法:
②时钟控件的使用
三.高级控件
1.SSTab控件
属性: Style属性 Tabs属性 TabsPerRow和Rows属性
TabOrientation属性 ShowFocusRect属性 Tab属性
事件: 方法:
2.Slider和UpDown控件的使用
四.鼠标与键盘
1.常见事件的各种参数的使用 和含义
MouseIcon和MousePointer决定了鼠标 的外形特征。
(1)MouseIcon属性
MouseIcon属性提供了一个自定义图标, 它在MousePointer属性设为99时使用,其 语法如下: Object. MouseIcon =LoadPicture (pathname) Object. MouseIcon =picture
其中,pathname指定包含自定义图标 文件的路径和文件名。picture是Form对象、 PictureBox控件或Image控件的MouseIcon 属性。
(2)MousePointer属性
所谓鼠标事件是由用户操作鼠标而引 发的能被VB中的各种对象识别的事件。 Click和DblClick事件是与鼠标有关的高级 事件,它们只能识别鼠标按下或双击动作。 可通过MouseDown、MouseUp、MouseMove事 件使应用程序对鼠标位置及状态的变化作 出响应(其中不包括拖放事件,后面的“拖 放”一节中将介绍拖放事件)。鼠标事件及 其说明如下。

Visual Basic教程 第8章 文件处理PPT课件

Visual Basic教程 第8章  文件处理PPT课件
要被复制的文件名,而destination用来指定要复制的 目的文件名。
人民邮电出版社
8.3.3 Shell函数 Shell函数的功能是执行一个可执行文件,同时返回一
个 Variant(Double),如果成功的话,返回代表这个程序的 任务 ID,若不成功,则会返回 0。它的语法结构如下:
Shell(pathname[,windowstyle])
8.1.3 控件 在工具箱中选择控件如图8-10所示。
人民邮电出版社
控件的功能是在程
序的运行过程中,在 Path 属性指定的目录中 , 控件将文件定位并列 举出来。
图8-10 在工具箱中的控件
人民邮电出版社
8.1.4 CommonDialog控件
CommonDialog控件的功能是提供一组标准的操 作对话框,进行诸如打开和保存文件,设置打印选 项以及选择颜色和字体等操作。
人民邮电出版社
8.4 文件系统
按照文件的存取方式及其组成结构可以分为两种类型: 顺序文件、随机文件;
按照文件的数据编码方式可以分为ASCII码文件和二 进制文件;
按照文件的特征属性可以分为系统文件、隐藏文件、 只读文件、普通文件和存档文件;
按照文件的数据性质来分可以分为程序文件和数据文 件。
人民邮电出版社
8.4.1 顺序文件 所谓的顺序文件,通常指的是普通的文本文件,文件中
的字符包括文本字符及控制字符,如“,”、“Chr(14)” 、换行符“CR,LF”、“Chr(13)”、“Chr(10)”等。数 据是以ANSI代码保存。
人民邮电出版社
1.顺序文件的打开 打开顺序文件的语法结构如下: Open pathname For mode [Access access] [lock] As [#] [Len=reclength]

精品课件-Visual Basic程序设计案例教程-第8章

精品课件-Visual Basic程序设计案例教程-第8章

第8章 应用程序界面设计
图8.4 菜单编辑器设置示例
第8章 应用程序界面设计
② “↑”和“↓”:单击“↑”按钮将所选取的菜 单项上移,单击“↓”按钮将所选取的菜单项下移。
③ “下一个”:在所选取的菜单项下方新增空白项 或选取菜单项。
④ “插入”:在光标所在位置的上方插入一个新的 菜单项。
⑤ “删除”:删除光标所在处的菜单项。 菜单编辑器下部是菜单项的显示区,输入的菜单项 将在此处显示出来。
第8章 应用程序界面设计
图8.6 建立分隔线
第8章 应用程序界面设计
注意:分隔线本身不是菜单项,它仅仅起分隔菜单项的作 用,因此不能带子菜单,不能设置“复选”等属性,也不能设 置快捷键。但必须设置“名称(M)”属性,否则在运行时会出 错。
到目前为止,第一个“文件”主菜单和它的第一级子菜单 已经全部建立,按照同样的方法可以建立“编辑”主菜单及其 “剪切”、“复制”、“粘贴”和“全选”子菜单,“格式” 主菜单及其“字体”和“颜色”子菜单,以及“颜色”的子菜 单项“红色”和“蓝色”。具体菜单项属性设置如表8.1所示。
第8章 应用程序界面设计
图8.2 下拉式菜单系统的基本结构
第8章 应用程序界面设计
2) 菜单编辑器 VB提供了设计菜单的工具——菜单编辑器。使用菜单编 辑器,可以轻松、快速地创建、编辑、修改主菜单、子菜单 和菜单项,并且可以设定菜单是否包括快捷键、快速键和复 选框,从而建立一个应用程序的菜单系统。 在设计菜单时,打开“菜单编辑器”的方法有两种:一 种是选择“工具”→“菜单编辑器”项,就会在屏幕上弹出 一个“菜单编辑器”窗口,如图8.3所示;另一种是在窗体 上点击右键,在弹出的菜单中选“菜单编辑器”项。
第8章 应用程序界面设计

Visual Basic(第八章)

Visual Basic(第八章)

第8章文件8.1 文件的概念计算机中最基本的操作就是运行程序和处理数据。

程序和数据都是以文件的形式存放在外部存储介质的,如磁盘、磁带、光盘等。

本章介绍的内容,主要针对数据文件。

8.1.1 文件的分类一、根据文件性质分类分为两大类:程序文件和数据文件。

二、根据存取方式分类分为两大类:顺序文件和随机文件。

顺序文件——只能从头到尾读/写文件中的数据。

随机文件——按记录号访问文件,可随机存取任意指定的记录。

三、根据编码方式分类分为两大类:ASCII文件和二进制文件。

ASCII文件——字符和数字用其对应的ASCII码存储,汉字存储则使用双字节的汉字字符集编码。

二进制文件——以二进制方式保存信息,该类文件不具有可读性,不能用文本编辑器建立或修改。

顺序文件以ASCII方式保存数据,随机文件以二进制形式保存数据。

8.1.2 数据文件的读写1.文件操作的两个基本概念读文件——从磁盘文件向计算机的内存传送数据,称为“输入”。

写文件——从计算机的内存向磁盘文件传送数据,称为“输出”。

2.数据文件的信息组织形式数据文件→记录→字段→字符或数字。

3.记录指针在一个打开的数据文件中,记录指针用来标识下一次将要读写的数据位置,也称为“文件指针”。

8.2 文件处理的基本步骤数据文件的处理,一般按以下3个步骤进行:1.打开(或建立)文件:一个数据文件,首先必须打开才能使用。

2.读写文件:数据文件处理的核心部分。

3.关闭文件:对于一个不再使用的文件,应执行关闭命令。

8.3 顺序文件8.3.1 顺序文件的建立、打开和关闭1.Open语句——建立或打开文件格式:Open文件名For读写方式As [#]文件号(1)文件名(字符串表达式):需要打开或建立的文件名,可包括驱动器和路径描述。

(2)读写方式:指定文件的存取方式:●Output顺序输出方式。

打开或建立一个顺序文件,并允许向文件输出数据。

●Input顺序输入方式。

打开一个顺序文件,指定从文件中读入数据。

《VisualBasic程序设计基础与实训教程》第8章多文档界面精品PPT课件

《VisualBasic程序设计基础与实训教程》第8章多文档界面精品PPT课件
(“标准EXE”)。 (2)单击【工程】|【添加MDI窗体】命令,弹出【添加MDI 窗体】对话框,选择【MDI窗体】,单击【打开】按钮,建 立MDI窗体。
现在,工程中含有一个MDI窗体(MDIForm1)和一个 标准窗体(Form1)。 注意:每个工程中只能有一个MDI窗体。如果工程中已经有 了一个MDI窗体,那么【工程】菜单上的【添加MDI窗体】命 令就不可使用。
【例8.1】创建一个文本书写器应用程序,可以新 建多个文档,并可以在每个文档中输入文字。运 行效果如图8.6所示。
图8.6 【例2.1】的运行效果
4.Screen 对象和Screen .ActiveForm属性
Screen 对象能提供当前窗体或控件的详细特性。Screen 有 多 个 属 性 , 如 ActiveControl 、 ActiveForm 、 ActiveReport 等。
2. 运行期间MDI子窗体的特性
(1)所有子窗体都在MDI窗体的内部区域显示,可以 像其他任何窗体一样移动子窗体和改变子窗体的大 小,但不能移出MDI窗体之外。
(2)当最小化一个子窗体时,它的图标将显示于MDI 窗体上,而不是在任务栏中。
(3)当活动子窗体有菜单时,它将显示在MDI窗体的 菜单栏中,而不是显示在子窗体上。
2. 创建子窗体
MDI 子 窗 体 是 一 个 MDIChild 属 性 为 True 的 标 准 窗 体 。 因 此 , 要 创 建 一 个 MDI 子窗体,应先通过单击【工程】|【添加 窗体】命令,创建一个新的标准窗体,或 者通过单击【工程】|【添加文件】命令, 打开一个存在的标准窗体,然后把它的 MDIChild属性设为True。
注意:启动子窗体时,其父窗体(MDI窗体)会自 动加载并显示。而启动MDI窗体时,其子窗体并不 会自动加载。

Visual Basic程序设计案例教程第8章

Visual Basic程序设计案例教程第8章

8.3.1 数组的概念
(4)为了区分不同的数组元素, 每一个数组元素都是通过数组 名和下标来访问的,有N个下标 的数组称为N维数组。 (5)使用数组时,必须对数组 进行先“声明”后使用。
8.3.1 数组的概念
3.数组的声明 数组的声明就是对数组名、数组元素的数据类型、 数组元素的个数进行定义。声明数组时,根据数组 元素个数是否已确定,将数组分为静态数组和动态 数组,声明时已确定数组元素个数的数组称为静态 数组,声明时还未确定数组元素个数的数组称为动 态数组;根据数组下标个数确定数组的维数,如果 一个数组的元素只有一个下标,刚称这个数组为一 维数组,有两个下标的数组称为二维数组,有多个 下标的数组称为多维数组。下面详细介绍一维数组、 二维数组、动态数组、控件数组的使用方法。
1.一维数组的声明
从上例可以看出,一维数组的声明格式如下: Dim 数组名(<下标>)[As <类型说明符>] 其中,数组名是用户定义的数组标识符,应该遵循标识符 的命名规则;尖括号中的下标表示数组的长度,即数组元 素的个数;类型说明符是数组元素的类型,可以是整型、 实型、字符型等;其中第一个元素的下标为0,第二个元 素的下标为1,后面元素的下标依次增长。例如: Dim a(10) As Integer 它表示定义了一维数组a,此数组有十一个元素,这11个 元素分别为a(0),a(1),a(2),a(3),a(4),a(5),a(6), a(7),a(8),a(9),a(10),每个元素的类型为整型。
8.3 运用数组存放学生信息
8.3.1 8.3.2 8.3.3 8.3.4 8.3.5 数组的概念 一维数组 二维数组 动态数组 控件数组
8.3.1 数组的概念
1.数组和数组元素的概念

Visual Basic 第8章 文件

Visual Basic  第8章 文件

通用对话框
1文件对话框 文件对话框包括“打开”和“另存为”对话框。使用“打 开”、“另存为”对话框可以设置文件对话框的属性。文 件对话框属性页中的属性和含义如表12-5所示。
属性标题 例如: 属性名称 含义
对话框标题 DialogTitle 设置对话框的标题,默认值为“打开”或“另存为” CommonDialog1.Fileter=”All Files(*.*)|*.*|位图(*.bmp)| 文件名称
通用对话框
VB6.0为用户提供了一组基于Windows标准的对话框, 称为通用对话框,即CommonDialog。包括“打开”对 话框、“另存为”对话框、“颜色”对话框、“字体” 对话框、“打印”对话框以及“帮助”对话框。 通用对话框不是标准控件,使用时必须先将该控件添 加到工具箱里。将CommonDialog添加到工具箱里的步 骤如下: 1.选择“工程”下拉菜单中的“部件”子菜单, 弹出“部件”对话框。 2.在“部件”对话框列表中选择“Microsoft Common Dialog Control6.0”项目,确保其前方 的复选框内出现“√”。 3.单击确定按钮。添加完成后工具箱里出现 CommonDialog的图标。具体操作如图12-10 所示。
设置对话框的一些选项,可 标志 Flags 以是多个值的组合。例如1 表示首次打开颜色对话框。
其他对话框
例如: Commondialog1.Showcolor Form1.BackColor=CommonDialog1.Color 表示将用户在“颜色”对话框中设置的颜色作为窗 体背景色。
其他对话框
任务1 任务1:理解文件的概念及分类 【任务目标】了解文件的结构和类型,熟 悉不同类型文件数据的组织形式。
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

8. FilesConsciousness ... does not appear to itself chopped up in bits. ... A “river”or a “stream” are the metaphors by which it is most naturally described.—William JamesI can only assume that a “Do Not File” document is filed in a “Do NotFile” file.—Senator Frank Church, Senate Intelligence Subcommittee Hearing, 1975ObjectivesIn this chapter you’ll learn:• To use file processing to implement a business app.• To create, write to and read from files.• To become familia r with sequential-access file processing.• To use classes StreamWriter and StreamReader to write text to and read textfrom files.• To organize GUI commands in menus.• To manage resources with Using statements and the Finally block of a Trystatement.Outline8.1 Introduction8.2 Data Hierarchy8.3 Files and Streams8.4 Test-Driving the Credit Inquiry App8.5 Writing Data Sequentially to a Text File8.5.1 Class CreateAccounts8.5.2 Opening the File8.5.3 Managing Resources with the Using Statement8.5.4 Adding an Account to the File8.5.5 Closing the File and Terminating the App8.6 Building Menus with the Windows Forms Designer8.7Credit Inquiry App: Reading Data Sequentially from a Text File8.7.1 Implementing the Credit Inquiry App8.7.2 Selecting the File to Process8.7.3 Specifying the Type of Records to Display8.7.4 Displaying the Records8.8 Wrap-UpSummary | Terminology | Self-Review Exercises | Answers to Self-Review Exercises | Exercises8.1. IntroductionVariables and arrays offer only temporary storage of data in memory—the data is lost, for example, when a local variable ―goes out of scope‖ or when the app terminates. By contrast, files (and databases, which we cover in Chapter 12) are used for long-term retention of large (and often vast) amounts of data, even after the app that created the data terminates, so data maintained in files is often called persistent data. Computers store files on secondary storage devices, such as magnetic disks, optical disks (like CDs, DVDs and Bluray Discs™), USB flash drives and magnet ic tapes. In this chapter, we explain how to create, write to and read from data files. We continue our treatment of GUIs, explaining how to organize commands in menus and showing how to use the Windows Forms Designer to rapidly create menus. We also discuss resource management—as apps execute, they often acquire resources, such as memory and files, that need to be returned to the system so they can be reused at a later point. We show how to ensure that resources are properly returned to the system when the y’re no longer needed.8.2. Data HierarchyUltimately, all data items that computers process are reduced to combinations of 0s and 1s. This occurs because it’s simple and economical to build electronic devices that can assume two stable states—one represents 0 and the other represents 1. It’s remarkable that the impressive functions performed by computers involve only the most fundamental manipulations of 0s and 1s!BitsThe smallest data item that computers support is called a bit, short for ―binary digit‖—a digit that can assume either the value 0 or the value 1. Computer circuitry performs various simple bit manipulations, such as examining the value of a bit, setting the value of a bit and reversing a bit (from 1 to 0 or from 0 to 1). For more information on the binary number system, see Appendix C, Number Systems.CharactersProgramming with data in the low-level form of bits is cumbersome. It’s preferable to program with data in forms such as decimal digits (that is, 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9), letters (that is, the uppercase letters A–Z and the lowercase letters a–z) and special symbols (that is, $, @, %, &, *, (, ), -, +, ", :, ?, / and many others). Digits, letters and special symbols are referred to as characters. The set of all characters used to write programs and represent data items on a particular computer is called that computer’s character set. Because computers process only 0s and 1s, every character in a computer’s character set is represented as a pattern of 0s and 1s. Bytes are composed of eight bits. Visual Basic uses the Unicode character set, in which each character is typically composed of two bytes (and hence 16 bits). You create programs and data items with characters; computers manipulate and process these characters as patterns of bits. FieldsJust as characters are composed of bits, fields are composed of characters. A field is a group of characters that conveys meaning. For example, a field consisting of uppercase and lowercase letters can represent a person’s name.Data HierarchyData items processed by computers form a data hierarchy (Fig. 8.1), in which data items become larger and more complex in structure as we progress up the hierarchy from bits to characters to fields to larger data aggregates.Fig. 8.1. Data hierarchy (assuming that files are organized into records). RecordsTypically, a record is composed of several related fields. In a payroll system, for example, a record for a particular employee might include the following fields:1. Employee identification number2. Name3. Address4. Hourly pay rate5. Number of exemptions claimed6. Year-to-date earnings7. Amount of taxes withheldIn the preceding example, each field is associated with the same employee. A data file can be implemented as a group of related records.1A company’s payroll file normally contains one record for each employee. Companies typically have many files, some containing millions, billions or even trillions of characters of information.1. In some operating systems, a file is viewed as nothing more than a collection ofbytes, and any organization of the bytes in a file (such as organizing the data into records) is a view created by the programmer.To facilitate the retrieval of specific records from a file, at least one field in each record can be chosen as a record key, which identifies a record as belonging to a particular person or entity and distinguishes that record from all others. For example, in a payroll record, the employee identification number normally would be the record key. Sequential FilesThere are many ways to organize records in a file. A common organization is called a sequential file in which records typically are stored in order by a record-key field. In a payroll file, records usually are placed in order by employee identification number. DatabasesMost businesses use many different files to store data. For example, a company might have payroll files, accounts receivable files (listing money due from clients), accounts payable files (listing money due to suppliers), inventory files (listing facts about all the items handled by the business) and many other files. Related files often are stored in a database. A collection of programs designed to create and manage databases is called a database management system (DBMS). You’ll learn about databases in Chapter 12 and you’ll do additional work with databases in Chapter 13, Web App Development with , and online Chapters 24–25.8.3. Files and StreamsVisual Basic views a file simply as a sequential stream of bytes (Fig. 8.2). Depending on the operating system, each file ends either with an end-of-file marker or at a specific byte number that’s recorded in a system-maintained administrative data structure for the file. You open a file from a Visual Basic app by creating an object that enables communication between an app and a particular file, such as an object of class StreamWriter to write text to a file or an object of class StreamReader to read text from a file.Fig. 8.2. Visual Basic’s view of an n-byte file.8.4. Test-Driving the Credit Inquiry AppA credit manager would like you to implement a Credit Inquiry app that enables the credit manager to separately search for and display account information for customers with• debit balances—customers who owe the company money for previously received goods and services• credit balances—customers to whom the company owes money• zero balances—customers who do not owe the company moneyThe app reads records from a text file then displays the contents of each record that matches the type selected by the credit manager, whom we shall refer to from this point forward simply as ―the user.‖Opening the FileWhen the user initially executes the Credit Inquiry app, the Button s at the bottom of the window are disabled (Fig. 8.3(a))—the user cannot interact with them until a file has been selected. The company could have several files containing account data, so to begin processing a file of accounts, the user selects Open...from the app’s custom File menu (Fig. 8.3(b)), which you’ll create in Section 8.6. This displays an Open dialog (Fig.8.3(c)) that allows the user to specify the name and location of the file from which the records will be read. In our case, we stored the file in the folder C:\DataFiles and named the file Accounts.txt. The left side of the dialog allows the user to locate the file on disk. The user can then select the file in the right side of the dialog and click the Open Button to submit the file name to the app. The File menu also provides an Exit menu item that allows the user to terminate the app.a) Initial GUI with Buttons disabled until the user selects a file from which to readrecordsb) Selecting the Open... menu item from the File menu displays the Open dialog inpart (c)c) The Open dialog allows the user to specify the location and name of the fileFig. 8.3. GUI for the Credit Inquiry app.Displaying Accounts with Debit, Credit and Zero BalancesAfter selecting a file name, the user can click one of the Button s at the bottom of the window to display the records that match the specified account type. Figure 8.4(a) shows the accounts with debit balances. Figure 8.4(b) shows the accounts with credit balances. Figure 8.4(c) shows the accounts with zero balances.a) Clicking the Debit Balances Button displays the accounts with positive balances(that is, the people who owe the company money)b) Clicking the Credit Balances Button displays the accounts with negative balances(that is, the people to whom the company owes money)c) Clicking the Zero Balances Button displays the accounts with zero balances (that is, the people who do not have a balance because they’ve already paid or have nothad any recent transactions)Fig.8.4. GUI for Credit Inquiry app.8.5. Writing Data Sequentially to a Text FileBefore we can implement the Credit Inquiry app, we must create the file from which that app will read records. Our first app builds the sequential file containing the account information for the company’s clients. For each client, the app obtains through its GUI the c lient’s account number, first name, last name and balance—the amount of money that the client owes to the company for previously purchased goods and services. The data obtained for each client constitutes a ―record‖ for that client. In this app, the accoun t number is used as the record key—files are often maintained in order by their record keys. For simplicity, this app assumes that the user enters records in account number order.GUI for the Create Accounts AppThe GUI for the Create Accounts app is shown in Fig. 8.5. This app introduces the Menu-Strip control which enables you to place a menu bar in your window. It alsointroduces ToolStripMenuItem controls which are used to create menus and menu items. We show how use the IDE to build the menu and menu items in Section 8.6. There you’ll see that the menu and menu item variable names are generated by the IDE and begin with capital letters. Like other controls, you can change the variable names in theProperties window by modifying the (Name) property.Fig. 8.5. GUI for the Create Accounts app.Interacting with the Create Accounts AppWhen the user initially executes this app, the Close menu item, the TextBox es and the Add Account Button are disabled (Fig. 8.6(a))—the user can interact with these controls only after specifying the file into which the records will be saved. To begin creating a fileof accounts, the user selects File > New... (Fig. 8.6(b)), which displays a Save As dialog (Fig. 8.6(c)) that allows the user to specify the name and location of the file into which the records will be placed. The File menu provides two other menu items—Close to close the file so the user can create another file and Exit to terminate the app. After the user specifies a file name, the app opens the file and enables the controls, so the user can begin entering account information. Figure 8.6(d)–(h) shows the sample data being entered for five accounts. The app does not depict how the records are stored in the file. This is a text file, so after you close the app, you can open the file in any text editor to see its contents. Figure 8.6(j)shows the file’s contents in Notepad.a) Initial GUI before user selects a fileb) Selecting New... to create a filec) Save As dialog displayed when user selects New... from the File menu. In this case,the user is naming the file Accounts.txt and placing the file in the C:\DataFilesfolder.d) Creating account 100e) Creating account 200f) Creating account 300g) Creating account 400h) Creating account 500i) Closing the filej) The Accounts.txt file open in Notepad to show how the records were written to the file. Note the comma separators between the data itemsFig. 8.6. User creating a text file of account information.8.5.1. Class CreateAccountsLet’s now study the declaration of class CreateAccounts, which begins in Fig. 8.7. Framework Class Library classes are grouped by functionality into namespaces, which make it easier for you to find the classes needed to perform particular tasks. Line 3 is an Imports statement, which indicates that we’re using classes from the System.IO namespace. This namespace contains stream classes such as StreamWriter (for text output) and Stream-Reader (for text input). Line 6 declares fileWriter as an instance variable of type Stream-Writer. We’ll use this variable to interact with the file that the user selects.Click here to view code image1' Fig. 8.7: CreateAccounts.vb2' App that creates a text file of account information.3Imports System.IO ' using classes from this namespace45Public Class CreateAccounts6Dim fileWriter As StreamWriter' writes data to text file7Fig. 8.7. App that creates a text file of account information.You must import System.IO before you can use the namespace’s classes. In fact, all namespaces except System must be imported into a program to use the classes in those namespaces. Namespace System is imported by default into every program. Classes like String, Convert and Math that we’ve used frequently in earlier examples are declared in the System namespace. So far, we have not used Imports statements in any of our programs, but we have used many classes from namespaces that must be imported. For example, all of the GUI controls you’ve used so far are classes in theSystem.Windows.Forms namespace.So why were we able to compile those programs? When you create a project, each Visual Basic project type automatically imports several namespaces that are commonlyused with that project type. You can see the namespaces (Fig. 8.8) that were automatically imported into your project by right clicking the project’s name in the Solution Explorer window, selecting Properties from the menu and clicking the References tab. The list appears under Imported namespaces:—each namespace with a checkmark is automatically imported into the project. This app is a Windows Forms app. The System.IO namespace is not imported by default. To import a namespace, you can either use an Imports statement (as in line 3 of Fig. 8.7) or you can scroll through the list in Fig. 8.8 and check the checkbox for the namespace you wish to import.Fig. 8.8. Viewing the namespaces that are pre-Imported into a Windows Forms app.8.5.2. Opening the FileWhen the user selects File > New..., method NewToolStripMenuItem_Click (Fig. 8.9) is called to handle the New... m enu item’s Click event. This method opens the file. First, line 12 calls method CloseFile (Fig. 8.11, lines 102–111) in case the user previously opened another file during the current execution of the app. CloseFile closes the file associated with this app’s StreamWriter.Click here to view code image8' create a new file in which accounts can be stored9Private Sub NewToolStripMenuItem_Click(sender As Object,10 e As EventArgs) Handles NewToolStripMenuItem.Click1112 CloseFile() ' ensure that any prior file is closed13Dim result As DialogResult' stores result of Save dialog14Dim fileName As String' name of file to save data1516' display dialog so user can choose the name of the file to save17Using fileChooser As New SaveFileDialog()18 result = fileChooser.ShowDialog()19 fileName = fileChooser.FileName ' get specified file name20End Using' automatic call to fileChooser.Dispose() occurs here2122' if user did not click Cancel23If result <> Windows.Forms.DialogResult.Cancel Then24Try25' open or create file for writing26 fileWriter = New StreamWriter(fileName, True)2728' enable controls29 CloseToolStripMenuItem.Enabled = True30 addAccountButton.Enabled = True31 accountNumberTextBox.Enabled = True32 firstNameTextBox.Enabled = True33 lastNameTextBox.Enabled = True34 balanceTextBox.Enabled = True35Catch ex As IOException36 MessageBox.Show("Error Opening File", "Error",37MessageBoxButtons.OK, MessageBoxIcon.Error)38End Try39End If40End Sub' NewToolStripMenuItem_Click41Fig. 8.9. Using the SaveFileDialog to allow the user to select the file into whichrecords will be written.Next, lines 17–20 of Fig. 8.9 display the Save As dialog and get the file name specified by the user. First, line 17 creates the SaveFileDialog object (namespace System.Windows.Forms) named fileChooser. Line 18 calls its ShowDialog method to display the SaveFileDialog (Fig. 8.6(c)). This dialog prevents the user from interacting with any other window in the app until the user closes it by clicking either Save or Cancel, so it’s a modal dialog. The user selects the location where the file should be stored and specifies the file name, then clicks Save. Method ShowDialog returns a DialogResult enumeration constant specifying which button (Save or Cancel) the user clicked to close the dialog. This is assigned to the DialogResult variable result (line 18). Line 19 uses SaveFileDialog property FileName to obtain the location and name of the file.8.5.3. Managing Resources with the Using StatementLines 17–20 introduce the Using statement, which simplifies writing code in which you obtain, use and release a resource. In this case, the resource is a SaveFileDialog. Windows and dialogs are limited system resources that occupy memory and should be returned to the system (to free up that memory) as soon as they’re no longer needed. Inall our previous apps, this happens when the app terminates. In a long-running app, if resources are not returned to the system when they’re no longer needed, a resource leak occurs and the resources are not available for use in this or other apps. Objects that represent such resources typically provide a Dispose method that must be called to return the resources to the system. The Using statement in lines 17–20 creates a SaveFileDialog object, uses it in lines 18–19, then automatically calls its Dispose method to release the object’s resources as soon as End Using is reached, thusguaranteeing that the resources are returned to the system and the memory they occupy is freed up (even if an exception occurs).Line 23 tests whether the user clicked Cancel by comparing result to the constant Windows.Forms.DialogResult.Cancel. If not, line 26 creates a StreamWriter object that we’ll use to write data to the file. The two arguments are a String representing the location and name of the file, and a Boolean indicating what to do if the file already exists. If the file doesn’t exist, this statement creates the file. If the file does exist, the second argument (True) indicates that new data written to the file should be appended at the end of the file’s current contents. If the second argument is False and the file already exists, the file’s contents will be discarded and new data will be written starting at the beginning of the file. Lines 29–34 enable the Close menu item and the TextBox es and Button that are used to enter records into the app. Lines 35–37 catch an IOException if there’s a problem opening the file. If so, the app displays an error message. If no exception occurs, the file is opened for writing. Most file-processing operations have the potential to throw exceptions, so such operations are typically placed in Try statements.8.5.4. Adding an Account to the FileAfter typing information in each TextBox, the user clicks the Add Account Button, which calls method addAccountButton_Click (Fig. 8.10) to save the data into the file. If the user entered a valid account number (that is, an integer greater than zero), lines 56–59 write the record to the file by invoking the StreamWriter’s WriteLine method, which writes a sequence of characters to the file and positions the output cursor to the beginning of the next line in the file. We separate each field in the record with a comma in this example (this is known as a comma-delimited text file), and we place each record on its own line in the file. If an IOException occurs when attempting to write the record to the file, lines 64–66 Catch the exception and display an appropriate message to the user. Similarly, if the user entered invalid data in the accountNumberTextBox or balanceTextBox lines 67–69 catch the FormatExceptions thrown by class Convert’s methods and display an appropriate error message. Lines 73–77 clear the TextBox es and return the focus to the accountNumberTextBox so the user can enter the next record. Click here to view code image42' add an account to the file43Private Sub addAccountButton_Click(sender As Object,44 e As EventArgs) Handles addAccountButton.Click4546' determine whether TextBox account field is empty47If accountNumberTextBox.Text <> String.Empty Then48' try to store record to file49Try50' get account number51Dim accountNumber As Integer =52 Convert.ToInt32(accountNumberTextBox.Text)5354If accountNumber > 0Then' valid account number?55' write record data to file separating fields by commas56 fileWriter.WriteLine(accountNumber & "," &57 firstNameTextBox.Text & "," &58 lastNameTextBox.Text & "," &59 Convert.ToDecimal(balanceTextBox.Text))60Else61 MessageBox.Show("Invalid Account Number", "Error",62MessageBoxButtons.OK, MessageBoxIcon.Error)63End If64Catch ex As IOException65 MessageBox.Show("Error Writing to File", "Error",66MessageBoxButtons.OK, MessageBoxIcon.Error)67Catch ex As FormatException68 MessageBox.Show("Invalid account number or balance",69"Format Error", MessageBoxButtons.OK,MessageBoxIcon.Error)70End Try71End If7273 accountNumberTextBox.Clear()74 firstNameTextBox.Clear()75 lastNameTextBox.Clear()76 balanceTextBox.Clear()77 accountNumberTextBox.Focus()78End Sub' addAccountButton_Click79Fig. 8.10. Writing an account record to the file.8.5.5. Closing the File and Terminating the AppWhen the user selects File > Close, method CloseToolStripMenuItem_Click (Fig. 8.11, lines 81–91) calls method CloseFile (lines 102–111) to close the file. Then lines 85–90 disable the controls that should not be available when a file is not open.Click here to view code image80' close the currently open file and disable controls81Private Sub CloseToolStripMenuItem_Click(sender As Object,82 e As EventArgs) Handles CloseToolStripMenuItem.Click8384 CloseFile() ' close currently open file85 CloseToolStripMenuItem.Enabled = False86 addAccountButton.Enabled = False87 accountNumberTextBox.Enabled = False88 firstNameTextBox.Enabled = False89 lastNameTextBox.Enabled = False90 balanceTextBox.Enabled = False91End Sub' CloseToolStripMenuItem_Click9293' exit the app94Private Sub ExitToolStripMenuItem_Click(sender As Object,95 e As EventArgs) Handles ExitToolStripMenuItem.Click9697 CloseFile() ' close the file before terminating app98 Application.Exit() ' terminate the app99End Sub' ExitToolStripMenuItem_Click100101' close the file102Sub CloseFile()103If fileWriter IsNot Nothing Then104Try105 fileWriter.Close() ' close StreamWriter106Catch ex As IOException107 MessageBox.Show("Error closing file", "Error",108MessageBoxButtons.OK, MessageBoxIcon.Error)109End Try110End If111End Sub' CloseFile112End Class' CreateAccountsFig. 8.11. Closing the file and terminating the app.When the user clicks the Exit menu item, method ExitToolStripMenuItem_Click (lines 94–99) respo nds to the menu item’s Click event by exiting the app. Line 97 closes the StreamWriter and the associated file, then line 98 terminates the app. The call to method Close (line 105) is located in a Try block. Method Close throws an IOExceptionif the file cannot be closed properly. In this case, it’s important to notify the user that the information in the file or stream might be corrupted.8.6. Building Menus with the Windows Forms DesignerIn the test-drive of the Credit Inquiry app (Section 8.4) and in the overview of the Create Accounts app (Section 8.5), we demonstrated how menus provide a convenient way to organize the commands that you use to interact with an app without ―cluttering‖ its user interface. Menus contain groups of related commands. When a command is selected, the app performs a specific action (for example, select a file to open, exit the app, etc.).Menus make it simple and straightforward to locate an app’s commands. They can also make it easier for users to use apps. For example, many apps provide a File menu that contains an Exit menu item to terminate the app. If this menu item is always placed in the File menu, then users become accustomed to going to the File menu to terminate an app. When they use a new app and it has a File menu, they’ll already be familiar with the location of the Exit command.The menu that contains a menu ite m is that menu item’s parent menu. In the Create Accounts app, File is the parent menu that contains three menu items—Ne w..., Close and Exit.Adding a MenuStrip to the FormBefore you can place a menu on your app, you must provide a MenuStrip to organize and manage the app’s menus. Double click the MenuStrip control in the Toolbox. This creates a menu bar (the MenuStrip) across the top of the Form (below the title bar; Fig.8.12) and places a MenuStrip icon in the component tray (the gray area) at the bottom of the designer. You can access the MenuStrip’s properties in the Properties window by clicking the MenuStrip icon in the component tray. We set the MenuStrip’s (Name) property to applicationMenuStrip.。

相关文档
最新文档