cse2207/cse3007 rapid applications programming with windows week 7
TRANSCRIPT
Topics Week 7
Database Programming Approach #3: Do it all Yourself
Data Sharing with the ClipBoard, OLEActiveX Controls
Approach #3 Do it all yourself!Programming the Recordset Establish a connection to a data source (e.g. db) Define a command (which table(s), which data) Execute the command If the command returns a recordset, then create
a recordset to hold the returned data Manipulate the records in the recordset as
required e.g. display fields from the ‘current record’ in form
controls add, delete, update records navigate through the recordset etc etc
Programming the RecordsetSteps: Create a connection to a data provider: Create
an ADO Connection Object, set its properties, e.g. ConnectionString, then Open the
connection (Ex1) Define the command to be executed on the
open connection: Create a Command object and set its properties CommandType e.g. adCmdTable
CommandText e.g. “Employees” (Example 2)
Perform the Execute method on the Command object: this may return a Recordset object if appropriate
The Execute Method
For a Command Object (Examples 2, 3)Set recordset = command.Execute( RecordsAffected,
Parameters, Options ) ‘ rows returned
command.Execute RecordsAffected, Parameters, Options ‘no rows returned
For a Connection Object: (Example 4)Set recordset = connection.Execute (CommandText,
RecordsAffected, Options ‘rows returned For a non-row-returning command string:
connection.Execute CommandText, RecordsAffected,
The Recordset Object Create a Command Object, set its properties
(Example 2), then use it with the Open method of the Recordset in order to obtain data e.g.
Dim rst As ADODB.Recordset
rstTitles.Open comTitles OR Create a Recordset object and populate it with
data without using a Command object, or a Connection Object (Example 5)
A Connection object is not required if a recordset is created from queries or tablenames, but it is more efficient if >1 recordset comes from a single connection
The Recordset Object
Write code to: (Ex5, 7, 8)display data from the recordset in form
controlsperform navigation within the recordset handle all data processing tasks
find, display, add, change, delete, cancel, save ensure that only valid data is written to the
database the interface display should always be complete,
correct, and consistent with the database: use CursorType, LockType properties, transaction processing
The Recordset ObjectTo Change a Record: Call the Update method of the Recordset Call the CancelUpdate method to cancel changes
made to the current record or to discard a newly added record.
If you move from the record you are adding or editing before calling the Update method, ADO will automatically call Update to save the changes.
The current record remains current after you call the Update method.
To Delete a record:
Call the Delete method of the Recordset Move (and check for EOF)
The Recordset Object
To Add a new record: Call the AddNew method of the Recordset Clear all the form controls Validate, then copy the form controls data to the
new record in the Recordset Call the Update method of the Recordset
The Close method closes the recordset and frees the resources allocated to it: rstTitles.Close
Recordsets are automatically closed when: You use the Close method on the recordset. The program executes an End statement.
Handling Run-Time Errors
Capture the error and handle it e.g.Private Sub cmdCalculate_Click()On Error GoTo ErrorHandler ‘OR, On Error……..rest of processing code ‘ Resume NextCommonExit:
Exit SubErrorHandler:MsgBox Err.Number & “ “ & Err.DescriptionResume CommonExitEnd Sub
See Example 4 for ADO errors
The Clipboard
An area of memory, managed by the Windows operation system
Enables running applications to share/exchange text and graphics.
The Clipboard object can be manipulated at run-time via its methods.
Only one item at a time is held in the Clipboard.
Used to support the standard tasks of Cut, Copy, and Paste
The Clipboard...
Select text at run-time via code:txtData.SetFocustxtData.SelStart = 0txtData.SelLength = Len(txtData.Text)
Check if user has selected text:If txtData.SelText = vbNullString OR
ALTERNATIVELY,If txtData.SelLength = 0 Then
mnuEditCut.Enabled = FalsemnuEditCopy.Enabled = False
End If
The Clipboard...
Place text into the Clipboard:Private Sub mnuEditCopy_Click()
Clipboard.ClearClipboard.SetText txtEdit.SelTexttxtEdit.Seltext = “” ‘IF THIS WAS CUT
End Sub ‘instead of COPY
Get text from the Clipboard:txtEdit.SelText = Clipboard.GetText()
The Clipboard...
Check the data format of Clipboard contents:If(Clipboard.GetFormat(vbCFBitmap)) = True Then
picPhoto.Picture = ClipBoard.GetData()ElseIf(Clipboard.GetFormat(vbCFText)) = True Then
If TypeOf Screen.ActiveControl Is TextBox ThenScreen.ActiveControl.SelText = ClipBoard.GetText()
End IfEnd If To place a picture into the Clipboard:ClipBoard.SetData picPhoto.Picture, vbCFBitmap
OLE: Object Linking and Embedding
Data shared/supplied is an OLE Object created by a server (source) application made available (exposed) to a container,
(client) applicationAllows developers to extend the functionality of
their applications by incorporating objects from existing applications. e.g. include a Word document, Excel spreadsheet in a VB application.
Allows visual editing of the OLE Object via in-place activation
OLE...
VB provides the OLE Container control to give the VB application access to one OLE object e.g. a WORD document
Allows objects to be inserted, changed at design and run-time
Can be bound to a Data Control: data from the OLE object can then be stored in a DB field
To date, the ADO Data Control does not bind to the OLE Container Control
OLE...
The OLE Container ControlProvides a place to insert or display OLE
objects (linked or embedded) from other applications
When you add an OLE Control to the VB form at design time, the Insert Object dialog box appears.
New Files may be embedded onlyExisting files may be embedded or linkedRight-click at run-time displays menu for e.g.
Edit, Open a Word doc; Replace a picture
OLE...
Linked OLE objects:Data associated with the object is stored by
the app. which created the object e.g. an Excel spreadsheet
The container app. (e.g. VB) only stores a link (pointer) reference to the OLE object, and the link displays a snapshot of the source data.
Any application with a link to the OLE object can change it e.g. a bitmap file. Changes are visible to all apps. with a link to that OLE object.
OLE...
Only an existing file may be used to create a Linked Object in VB
An app. with a linked OLE object occupies less disk space than one with an embedded OLE object
Edit a linked OLE object by double-clicking the OLE control. This starts up its server application e.g. Excel. Make changes, Save and Exit (returns back to VB)
Use the Update method to refresh a linked OLE object e.g. in the Form’s Load event: oleYearTotals.update
OLE...
Embedded OLE objects:Data associated with the object is copied to
the container app. when the object is first created
From then on it is owned and stored by the container application
No other application has access to the data in an embedded OLE object
Both New and Existing Files may be used to create embedded OLE objects
OLE... Edit the data in an embedded OLE object by double-
clicking, or right-clicking the OLE control. Choose “Open”:
the server application menu bar e.g. WORD, replaces the VB application (form) menu bar
Close the document and return to the VB app. Choose “Edit”:
the server app menu bar will ‘combine’ with the VB app. Menu bar, according to the ‘NegotiateMenus’ option specified in the Menu Editor
After editing the data, no need to save|exit, just press ESC key to remove the WORD menu and return to the VB form menu bar
OLE...
The OLE Container Control Set the SizeMode property to 2-AutoSize so the
control shows all the object data. Can save the OLE object data into a file via the OLE
control methods SaveToFile and ReadFromFile (Examp 9)
When an OLE document is activated, the OLE server program must be loaded. To avoid the delay, load it e.g. while the Splash screen is showing:
Dim dbWordID As DoubledbWordID = Shell(“C:\MSOFFICE\WINWORD\
WINWORD.EXE”, vbMinimizedNoFocus)
OLE AutomationAllows applications to provide their own
objects in a consistent way to other applications. Such objects can be: linked, embedded at design or run-time created, manipulated by the client
application via the OLE object’s properties and methods made available by the server application
The objects, functions, properties, methods supported by an OLE Automation application are defined in the application’s object library
OLE Automation...
Project|References|Microsoft Excel 8.0 Object Library
View Attributes, Methods via View|Object Browser
Uses: e.g. Create an Excel spreadsheet object, place several ranges of labels and numbers on it, mathematically manipulate the numbers and create a chart, then print both the sheet and chart, all without your application user seeing the Excel application itself! (See Example 10)
OLE Automation...Q: Which object methods do I use to perform
certain functions in e.g. Word, ExcelA: Use their macro recorders to generate Visual
Basic for Applications code:1. Start the macro recorder (under Tools,
usually)2. Perform the functions you want to do in the
application3. Stop the macro recorder4. Copy the VBA code into your VB application
add the create objects code to start, then destroy at end
ActiveX
ActiveX “is a blanket technology promoted by Microsoft that defines a communications standard between applications.” Norton 1998 Includes custom controls bought or built is a major component of MS’s COM based on the concept of an application
built from several different components bound with a programming language like VB
ActiveX Controls
An ActiveX Control is a self-contained object with specific behaviour and capability: an “encapsulated operation”
Can sometimes accept input, perform some action, make results available or call other controls.
Need to define what the component (ActiveX control) will do its visible interface (if any) what methods, properties it will expose (if any)
ActiveX Controls
To create an ActiveX Control: Enhance one or more existing controls
add new properties, methods, events; or expose, modify existing ones: better not to modify
these become the ‘constituent’ controls
Create a control from scratch (Not here) Code and visual description of the ActiveX
object is stored in a UserControl module Can also have Property Page module (Not
here)
ActiveX Controls
Author Creates the visual interface for the control,
writes code for its properties, methods, events
Developer At design time, places an instance of the
control on a form, and uses the properties, methods, events that have been made available for the control by the author
User At run time, interacts with the control,
generates events that the author and/or developer have made available.
ActiveX Controls...
Start a new ActiveX Control Project Name is UserControl1, design the control’s
interface using toolbox controls. Add code to the UserControl’s Initialize
event to ‘set-up’ the interface if necessary Write code for the constituent controls e.g.
select all the text in a Text Box’s GotFocus event
‘Shrink’ the control’s design area to enclose just the interface controls.
Click File|Save MyActiveX As, and save with a .ctl extension
ActiveX Controls...
Click the Close Button on the Project1 - XXXXX (User Control) window: your new control will appear in the toolbox
To test the control, add a standard .EXE project to the application, then click and drop the ActiveX control onto Form1.
Run the project (you may need to click ‘set as Start Up’ in Project Explorer Pop-Up menu), and test the control
To include the ActiveX control in a project, start a new Project, then Project|Add User Control, then the Existing Tab, and the .ctl file
ActiveX Controls The UserControl object automatically supports
properties, events, methods made available from the container (a VB form) e.g. Name, TabIndex, Font, TextAlign, GotFocus,
LostFocus To expose existing events of the constituent
controls: Declare the event as Public in the General
Declarations section of the User Control then Raise (generate) the Event by invoking it from
the specific event of the constituent control e.g. the Click event of a Text box
The new event belongs to the User Control, and can accessed by a developer. (Examp 11)
ActiveX Controls
Can expose existing properties of the constituent controls e.g. allow a developer to read and write the Text property of a constituent text box: To read the Text value, create a Property
Get procedure in the User Control To write (change) the Text value, create a
Property Let procedure, then call the PropertyChanged method of the User Controlnotifies the container that a property
has been modified (Example 12)