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 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:// 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 downloads/ updates.asp) and Client Access service pack SF62608 (available here at 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 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:

• HiT Software:

• IBM Client Access OLE DB Support: 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





  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things

    Read Node.js for Enterprise IBM i Modernization Now!


  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!


  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.


  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline



  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.


  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact


  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using as a pre-built development environment



  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.



  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.



  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails


  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.



  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave 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.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY 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.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.