The data-bound Grid control is one of the most flexible and powerful Visual Basic controls. If you have Used microsoft Access, you’ll he familiar with this control. The data-bound Grid control looks a lot like the MSFlexGrid control (discussed in chapter 9), with two major differences:
- It populated automatically from a RecordSet.
- It has built-in data-entry mechanisms with which you can edit the Record- Set (if it can be updated).
To fill the control with the data in a RecordSet, all you have to do is to set its Data- Source property to a Data control. The grid is filled with the rows of the RecordSet. Because of the two-dimensional arrangement of the data on the control, you can really see the structure and contents of the entire RecordSet. I used this control to
depict RecordSets in some of the figures at the beginning of this chapter. I also used this control to display the results of the SQL statements in the SQLExec application, which we are going to look at next.
VB6 at Work: The SQLExec Projected
Earlier in this chapter, we used the SQLExec application to experiment with SQL statements. Now, we are going to build this application. Follow these steps:
- Start a new Standard EXEproject.
- To add the data-bound Grid control to the Toolbox, right-click the Toolbox, and select Components.
- In the Components dialog box, check the Microsoft Data Bound Grid Control checkbox. We will also use the Common Dialogs control in’this project, so also check the Microsoft Common Dialogs Control 5.0 checkbox, and then click the Close button.
- Draw the controls you see on the Form shown in Figure 17.23. In addition to the visible controls on the Form, there is a Common Dialogs control (which is invisible at runtime) and a Data control (Data1), whose Visible property is set to False.
- The TextBox control on which the SQL statements are typed is called txtSQL. Set its Multi line property to True, and set its Scroll bars property to 2-Vertical.
- Now you can program the buttons. The code for the Open Database button opens the File Open dialog box, in which you can select the database with which you want to work. The name of the database is displayed on the Label control next to the Command button:
- The Execute SQL button retrieves the SQL statement from the txtSQL textbox and assigns it to the Data control’s RecordSource property with the following statement:
The OnError statement traps any error in the execution of the SQL statement and displays it in a message box, Assigning a new value to.the control’s Record- Source property doesn’t update the content of the control. You must also call the Refresh method of the Data control to read the new data from the database and to force an update.