⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch18.htm

📁 delphi自学的好教材!特别适合刚刚起步学习delphi的人员!同样对使用者具有参考价值!
💻 HTM
📖 第 1 页 / 共 4 页
字号:
    Delete(S, 1, P);    Table.FieldByName(`FAX').Value := S2;    { We might get a key violation exception if we try to add a }     { record with a duplicate customer number. If that happens, }     { we need to inform the user, cancel the edits, put the     }     { put the Table back in edit mode, and continue processing. }     try      Table.Post;    except      on EDBEngineError do begin        MessageBox(Handle,          `Duplicate Customer Number', `Key Violation', 0);        Table.Cancel;        Table.Edit;        Continue;      end;    end;  end;  { All done with the TStringList so it. }   Lines.Free;  { We won't the Table so that the Table's data shows }   { in the DBGrid. VCL will the Table and Datasource  }   { for us. }   {Table.Free; }   {Datasource.Free; } end;</PRE><PRE>end. </PRE><H2><A NAME="Heading5"></A>Using Data Modules</H2><P>As you know by now, setting up database components is easy in Delphi. Still, thereis some time involved, even for the simple examples you have been writing.</P><P>You have to place a Table or Query component on the form and choose the databasename. Then you have to set the table name (for a Table) or SQL property (for a Query).You might have to set other properties, depending on how you are using the database.You might also have several events to handle. Next, you have to place a DataSourcecomponent on the form and attach it to the table or query. If your application makesuse of a Database component, you have to set that component's properties and eventsas well. None of this is hard, but it would be nice if you could do it all just oncefor all your programs. Data modules enable you to do exactly that.</P><P>At the base level, data modules are really just specialized forms. To create adata module, open the Object Repository and double-click the Data Module icon. Delphicreates the data module and a corresponding source unit just as it does when youcreate a new form. You can set the Name property of the data module and save it todisk, again, just like a form.</P><P>After you create the data module, you place data access components on it. Thenyou set all the properties for the data access components as needed. You can evencreate event handlers for any components on the data module. When you have set everythingjust the way you want it, save the data module. Every form in your application canthen access the data module.</P><P><H3><A NAME="Heading6"></A>Setting Up a Sample Data Module</H3><P>A simple exercise will help you understand data modules better. First, you'llset up the data module, and then you'll put it to work:</P><DL>	<DT></DT>	<DD><B>1. </B>Create a new application. Change the main form's Name property to MainForm.	Save the project. Save the main form as DSExMain.pas and the project as DSExampl.dpr.	<P>	<DT></DT>	<DD><B>2. </B>Choose File|New. When the Object Repository appears, double-click the	Data Module icon to create a new data module. The Form Designer displays the data	module. Change the Name property to DBDemos.	<P>	<DT></DT>	<DD><B>3. </B>Click on the Data Access tab on the Component palette. Place a Table	component on the data module. Change the DatabaseName property to DBDEMOS and the	TableName to ANIMALS.DBF. Change the Name property to AnimalsTable.	<P>	<DT></DT>	<DD><B>4. </B>Place a second Table component on the data module. Set the DatabaseName	property to DBDEMOS and the TableName property to BIOLIFE.DB. Change the Name property	to BiolifeTable.	<P>	<DT></DT>	<DD><B>5. </B>Place a DataSource component on the data module. Change its Name property	to Animals and its DataSet property to AnimalsTable.	<P>	<DD><B>6. </B>Place another DataSource component on the data module. Change this	data source's Name to Biolife and its DataSet property to BiolifeTable. Your data	module now looks like Figure 18.2.</DL><P><A HREF="javascript:popUp('28671802.gif')"><B>FIGURE 18.2.</B></A><B> </B><I>Thefinished data module.</I></P><DL>	<DT><I></I></DT>	<DD><B>7. </B>Double-click on the background of the data module. An OnCreate event	handler will be created for the data module. Type this code in the event handler:	<P></DL><BLOCKQUOTE>	<PRE>AnimalsTable.Open;BiolifeTable.Open;</PRE></BLOCKQUOTE><PRE></PRE><DL>	<DT></DT>	<DD><B>8. </B>Save the project. When prompted, save the data module as DataMod.pas.	<P></DL><H3><A NAME="Heading7"></A>Adding to Your Data Module</H3><P>Now let's put the new data module to use. You are going to create two buttonsfor the application's main form. One button will display a form that shows the Animalstable, and the other will display the Biolife table. Here goes:</P><DL>	<DT></DT>	<DD><B>1. </B>Create a new form. Change the form's Caption property to Animals Form	and the Name property to AnimalsForm.	<P>	<DT></DT>	<DD><B>2. </B>Choose File|Use Unit. Choose the DataMod unit from the Use Unit dialog	and click OK. The data module is now accessible from the main form.	<P>	<DT></DT>	<DD><B>3. </B>Place a DBGrid component and a DBNavigator component on the form. Select	both the DBGrid and DBNavigator components. Locate the DataSource property in the	Object Inspector and click the drop-down arrow next to the property. You will see	the following displayed in the list of available data sources:	<P></DL><BLOCKQUOTE>	<PRE>DBDemos.AnimalsDBDemos.Biolife</PRE></BLOCKQUOTE><PRE></PRE><DL>	<DT></DT>	<DD>Choose the DBDemos.Animals data source.	<P>	<DT></DT>	<DD><B>4. </B>Save the unit as DSExU2.pas (or a more meaningful name if you like).	<P>	<DT></DT>	<DD><B>5. </B>Again, create a new form for the project. Repeat steps 1 through 3,	but this time choose DBDEMOS.Biolife for the data source and change the Caption to	BioLife Form. Change the Name property to BiolifeForm. Save the form as DSExU3.pas.	Figure 18.3 shows the Delphi IDE after completing this step.	<P></DL><H3><A NAME="Heading8"></A>Running the Data Module</H3><P>These steps demonstrate that after you create a data module, you can use the componentson that data module from anywhere in your program. All you have to do is use theunit for the data module, and then all data-aware components will be capable of detectingthe data module. Let's finish this application so that you can try it out:</P><DL>	<DT></DT>	<DD><B>1. </B>Place a button on the main form. Change its Caption property to Show	Animals.	<P>	<DT></DT>	<DD><B>2. </B>Double-click the button to generate an OnClick handler for the button.	Type this code in the event handler:	<P></DL><BLOCKQUOTE>	<PRE>AnimalsForm.Show;</PRE></BLOCKQUOTE><PRE></PRE><DL>	<DT></DT>	<DD><B>3. </B>Drop another button on the form. Change its Caption property to Show	Biolife.	<P>	<DT></DT>	<DD><B>4. </B>Create an OnClick event handler for this button and type the following	code in the event handler:	<P></DL><PRE>BiolifeForm.Show;</PRE><DL>	<DT></DT>	<DD><B>5. </B>Choose File|Use Unit. Choose the DSExU2 unit and click OK.	<P>	<DT></DT>	<DD><B>6. </B>Repeat step 5 to include the DSExU3 unit.	<P></DL><P>Now you can run the program. When you click a button, the appropriate form willappear. Figure 18.4 shows the program running.</P><P><A HREF="javascript:popUp('28671803.gif')"><B>FIGURE 18.3.</B></A> <I>The secondform completed.</I></P><P><A HREF="javascript:popUp('28671804.gif')"><B>FIGURE 18.4.</B></A><B> </B><I>Theprogram running with both forms displayed.</I></P><P>Data modules make it easy to set up your database components once and then reusethose components over and over. After you create a data module, you can save it tothe Object Repository, where it is always available for your use.</P><P><H2><A NAME="Heading9"></A>Creating Reports</H2><P>A database program is not complete without some way of viewing and printing data,and that is where reports enter the picture. Up to this point, you have been lookingat ways to view individual records or multiple records with the DBGrid component.These methods might be perfect for some applications, but sooner or later you willneed more control over the viewing of records.</P><P>Besides viewing the data onscreen, you will almost certainly need to print thedata. A database application that can't print is not very useful. Delphi's QuickReportcomponents enable you to view and print your data with ease.</P><P><H3><A NAME="Heading10"></A>QuickReport Overview</H3><P>Before you can create a report, you need an overview of how the QuickReport componentswork.</P><P><H3><A NAME="Heading11"></A>The QuickRep Component</H3><P>The base QuickReport component is the QuickRep component. This component actsas a canvas on which you place the elements that your report will display (I'll discussthe report elements soon).</P><P>The QuickRep component has properties that affect the way the report will appearwhen printed. For example, the Page property is a class containing properties calledTopMargin, BottomMargin, LeftMargin, RightMargin, Columns, Orientation, PaperSize,and so on.</P><P>The PrinterSettings property is also a class. This property has its own properties,called Copies, Duplex, FirstPage, LastPage, and OutputBin. The ReportTitle propertyis used to display the print job description in the Windows Print Manager and inthe title bar of the QuickReport preview window. The Units property controls whethermargins are displayed in millimeters, inches, picas, or other choices. The DataSetproperty is used to set the dataset from which the report's data will be obtained.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> The DataSet property must be set and the associated dataset must	be active before anything will show up in the report. <HR></BLOCKQUOTE><P>Primary QuickRep methods include Preview and Print. The Print method, as its nameimplies, prints the report. The Preview method displays a modal preview window. Thepreview window includes buttons for viewing options, first page, last page, previouspage, next page, print, print setup, save report, open report, and close preview.Figure 18.5 shows the QuickReport preview window at runtime.</P><P><A HREF="javascript:popUp('28671805.gif')"><B>FIGURE 18.5.</B></A><B> </B><I>TheQuickReport preview window.</I></P><P>QuickRep events of note include OnPreview and OnNeedData. You can use the OnPreviewevent, instead of the default preview window, to provide a custom preview window.When using a data source other than a VCL database, you use the OnNeedData event.For example, you can create a report from a string list, an array, or a text file.</P><P><H3><A NAME="Heading12"></A>Report Bands</H3><P>A QuickReport is composed of bands. <I>Bands</I> come in many different types.A basic report has at least three types: a title band, a column header band, anda detail band. The title band contains the report title, which is displayed onlyon the first page of the report. The column header band is used to display the columnheaders for the fields in the dataset; the column header appears at the top of everypage. Some reports, such as a report used to generate mailing labels, do not havea column headers band.</P><P>The detail band is the band that does all the work. On the detail band you placeany data that you want in the report. You define the contents of the detail band,and QuickReport repeats the detail band for every record in the dataset. In a minuteyou'll do an exercise that illustrates how the different bands work.</P><P>Other commonly used band types include page header, page footer, group header,group footer, and summary bands. The QRBand component defines a QuickReport band.The BandType property is used to specify the band type (title, detail, header, footer,and so on).</P><P>The bands automatically arrange themselves on the QuickRep component, based onthe band's type. For example, if you place a QRBand on the report and change itsBandType to rbPageFooter, the band will be moved below all other bands. Likewise,a page header band will be placed above all other bands.</P><P><H4>QuickReport Design Elements</H4><P>QuickReport design elements come in three forms. The first form includes componentsfor text labels, images, shapes, headers, footers, and so on. These components areprimarily used to display static design elements. For example, the report title isusually set once and then doesn't change. Another example is a graphic used to displaya company's logo on the report. The components in this group are very similar tothe standard VCL components. The QRLabel component resembles a standard Label component,a QRImage is similar to the VCL Image component, the QRShape component is similarto the regular Shape component, and so on. Use these components to design the staticportions of your reports.</P><P>The second category of elements contains QuickReport versions of the standardVCL data-aware components. These components are placed on the detail band of a report.Components in this group include the QRDBText, QRDBRichEdit, and QRDBImage components.Data is pulled from the dataset and placed into these components to fill the bodyof the report.</P><P>The third group of QuickReport components includes the QRSysData component andthe QRExpr component. The QRSysData component is used to display page numbers, thereport date, the report time, the report title, and so on. The QRExpr component isused to display calculated results. The Expression property defines the expressionfor the calculation. The Expression property has a property editor called the Expressionbuilder that is used to define simple expressions. An expression might be simple,such as multiplying two fields, or complete with formulas such as AVERAGE, COUNT,or SUM.</P><P><H3><A NAME="Heading13"></A>Creating Reports by Hand</H3><P>Certainly the best way to write truly custom reports is by hand. That might sound

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -