Mon, Jul
4 New Articles

Using the Visual Basic DataGrid Control

Visual Basic
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Version 6.0 of Microsoft Visual Basic (VB) shipped with several enhancements designed to facilitate database programming using OLE DB and ODBC data access methods. GUI controls—such as DataGrid, DataList, and DataCombo—were also added to allow programmers to quickly prototype data-oriented applications. These controls were designed to take advantage of the ActiveX Data Object (ADO) component library. ADO implements a simplified, access pattern-neutral interface to OLE DB, Microsoft’s universal database connector layer. Many vendors implement OLE DB “providers,” or drivers, written to the OLE DB spec so that databases, including the AS/400’s, may be accessed with ADO. With the new controls and ADO, it is possible to use VB to create simple, functional database apps with little or no code. Understanding how these controls work is the key to writing more sophisticated applications with ADO and OLE DB in all Windows environments.

The new data access controls of VB 6.0 belong to a class of controls known as “data aware,” or “data bound,” controls. These controls can be bound to rows and columns of a relational database source, greatly reducing the programming legwork required to manipulate the data. In essence, you predefine the relationships between the data source and the controls that will display and manipulate the data. Thereafter, any changes to the underlying data source are automatically reflected in the control’s display. Likewise, any user changes to editable elements of the control can be made to the underlying data. Perhaps the most anticipated and useful of the VB 6.0 controls is the DataGrid.

Introducing the DataGrid

The DataGrid control combines a data display function (such as the VB Label control) and a data navigation function (such as the VB Adodc control) into a single control. DataGrid sports a highly functional spreadsheet-style user interface. It has many special features for formatting, displaying, updating, and manipulating the data displayed in its rows and columns. As an example for this article, I have used DataGrid and an extremely small amount of code to access an AS/400 file named ORDERS (the file, contained in a *SAVF object, and example code can be downloaded from the MC Web site at www.midrangecomputing.com/mc). You can use ADO objects to open the database

connection and file and to connect those objects to the DataGrid, which will navigate and display the contents of the file.

Before diving into the example, note that the DataGrid and all data-aware controls are fully documented in the Help system that comes with VB 6.0. That documentation is also available on the Web at http:// msdn.microsoft.com/library/devprods/vs6/ vbasic/vbcon98/vbcondataawarecontrols.htm. The example code was developed with Visual Studio on Windows NT 4.0 Workstation with Windows NT Service Pack 3.

Also Visual Studio Service Pack 3 (available at http://msdn.microsoft.com/vbasic/ downloads/ updates.asp) and Client Access service pack SF62608 (available here at www.as400.ibm.com/clientaccess/casp.htm) were installed.

For the example, start with a new Standard EXE project with VB’s Project Wizard (select New Project from the File menu). If it is not already there, use the Components Wizard (also found in the Project menu) to add the Microsoft DataGrid Control to the control palette, as shown in Figure 1. If you already have VB 5.0 on your development machine, be careful not to confuse the DataGrid control with the Data Bound Grid control.

Drag and drop a DataGrid component onto the prototype form. At this point, the DataGrid looks like an empty spreadsheet with two cells. You could simply hook it up to an instance of the Adodc control and set Adodc’s properties for the connection and file (and not have to write a single line of code!). Instead, as an exercise, I’ll have you add the code to open the connection to the data and hook it up to the DataGrid. First, however, you need to add a reference to the ADO component library. From the VB Project menu, select the References option. Select the Microsoft ActiveX Data Objects Library from the list of available references. On the View menu, select Code. Add the following code:

Private Sub Form_Load()

Dim Connection As New ADODB.Connection

Dim Records As New ADODB.Recordset

‘ important against as400

Connection.CursorLocation = adUseClient

Connection.Open “Provider=IBMDA400;" _

+ "Data Source=ASH”

Records.Open “ORDERS”, Connection, _

adOpenStatic, adLockOptimistic, _


Set DataGrid1.DataSource = Records
End Sub

The Form_Load subroutine is called from the VB runtime engine just before the form is displayed. The code uses two ADO objects: Connection (to open the database connection) and Recordset (to open the file), respectively. The Connection.Open method call specifies the IBM Client Access OLE DB provider and your AS/400. The Records.Open method call specifies the file to open (via the ORDERS and adCmdTable parameters), the open connection to use (the Connection parameter), and the locking/access (the adOpenStatic and adLockOptimistic parameters). Finally, you set the DataSource property of DataGrid1 (the default name of the DataGrid dropped into the prototype form) to the Records object.

Click the Start button, and the DataGrid will display the contents of the ORDERS file. Notice that the scrollbars control the display and, via the Recordset object, access the records of the file.

Figure 2 shows the DataGrid in action. Note that the DataGrid has many properties that affect the display of the data. By clicking on the button at the beginning of each row, you select that row as the current row. Your VB program can thus reference the user’s selected row at runtime via the DataGrid’s Bookmark property. By default, the cells of the DataGrid are editable, allowing the user to change the data in the underlying source if the

OLE DB provider permits. There are simply too many interesting DataGrid features to list here; see the references section at the end of this article for more information.

Because of the intuitive binding between the ADO Recordset and the DataGrid control, it is very easy to change the amount of data displayed by simply changing the query. For example, change the Records.Open method call just listed with the following code:

Records.Open "select "+_


"from ORDERS", adOpenStatic_

adLockOptimistic, adCmdText

The previous simple file access format is then replaced with an SQL query, as specified by the adCmdText parameter. This query reduces the amount of fields shown for each row in the DataGrid.

Complex-bound Controls and the AS/400

The DataGrid control is known as a complex-bound control, another subclass of data- bound controls. Complex-bound controls can be bound to entire rows of a data source, whereas simple-bound controls, such as Label or TextBox, can be bound only to a single field. Complex-bound controls are highly integrated with the underlying OLE DB data access engine so that they can efficiently and flexibly access the rows of the data sources they are bound to. Controls like the DataGrid, therefore, are best used with databases that have a fully functional OLE DB provider. In particular, OLE DB driver functionality, such as row references (known as bookmarks) and multirecord locking, is critical. Unfortunately, the OLE DB providers for DB2/400 support neither of these features. Note the following code from the DataGrid example:

‘ important against as400

Connection.CursorLocation = adUseClient

This code sets the CursorLocation property of the database connection. It tells the OLE DB provider whether to use client-side or server-side “cursors,” also known as record pointers, for the connection. Remove this line of code and you will see “not bookmarkable” or similar errors. Native DB2/400 and Client Access do not support OLE DB’s server-side cursor semantics, so this line of code is required to indicate the use of client-side cursors. The intent of server-side cursors is to optimize the connection when you might want only a few records and to allow the contents of the Recordset to be efficiently updateable. The effect of this limitation is that the entire contents of the file or query are fetched from the server when the Recordset object is opened, resulting in very poor performance. For large files, this causes a significant delay in the DataGrid example. Of course, one way to prevent this is to use an SQL statement with very narrow selection criteria to restrict the number of records retrieved from the file to a small subset of the records in the file.

It should be mentioned that Client Access also supports a non-SQL, record-oriented access methodology, but it requires secondary, IBM-supplied Component Object Model (COM) objects, making it a less portable solution. Note also that the Recordset Open method in these examples specifies the adOpenStatic parameter, setting a static cursor type for the Recordset’s CursorType property. Data returned in such a method call is static; you can’t use the ADO methods provided to add, update, or delete records in the Recordset and expect those changes to be reflected on the server. The only way to make changes to a file via SQL with IBM’s OLE DB provider is through SQL language statements. All known SQL-enabled OLE DB providers for the AS/400 suffer from the cursor location limitation; however, HiT Software’s AS/400 OLE DB provider does allow a dynamic cursor type. Thus, in the DataGrid example program, you could change the data in the cells, but, unless

you are using the HiT OLE DB provider and dynamic cursors, the changes won’t be made to the file. (Visit Hit Software’s Web site at www.hit.com for a free trial download of its OLE DB provider.)

It can be tricky to effectively use VB 6.0’s DataGrid control with the current OLE DB providers for the AS/400, but, with an understanding of how the underlying OLE DB provider is being exercised, you can pick the right problems to solve with this elegant control.


• Client Access Service Pack SF62608 download: www.as400.ibm.com/clientaccess/casp.htm

• HiT Software: www.hit.com

• IBM Client Access OLE DB Support: www.as400.ibm.com/clientaccess/oledb Figure 1: The Visual Basic Components Wizard lets you add DataGrid.

Using_the_Visual_Basic_DataGrid_Control04-00.png 400x355

Using_the_Visual_Basic_DataGrid_Control05-00.png 400x213

Figure 2: The example program reads the ORDERS file and displays its contents in the DataGrid.



Support MC Press Online


Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: