Using ADO and the ListView control

Level:
Level2

Written By TheVBProgramer.

(Customer Table Maintenance Example)

This VB6 tutorial demonstrates uses of ADO not covered in other tutorials on this site. The sample project presented here is a simple "one-table" database application. It works with a table of customer data (name, address, phone, etc.) and allows the user to view, add, update, and delete customer records. Also, this sample project uses the ListView control to display the records that the application will be working with. The use of the ListView control is covered at the end of this topic.

The sample application uses an MS-Access database called Cust.mdb, consisting of one table called Customer. The columns of the table are defined as follows:

Column Name

Data Type

CustID

Number (Long Integer)

LastName

Text (50)

FirstName

Text (50)

Address

Text (50)

City

Text (25)

State

Text (2)

Zip

Text (5)

PhoneNumber

Text (10)

Screen-shots of the sample application are shown below.

Initially, this screen is in "read-only" mode; only the list portion is active. The data entry fields on the bottom half of the screen are grayed out are not enterable. The buttons to add, update, and delete are available; the buttons to save or cancel are not available. A screen-shot of the screen in this state is shown below:

To add a customer, click the "Add" button. This will enable the fields on the bottom half of the screen. The buttons to add, update, and delete will become unavailable; the buttons to save or cancel will be available. A screen-shot of the screen in this state is shown below:

You can then enter the values for the new record:

When you are done entering data into the fields, click the Save button, which will cause the new record to be added to the list and will cause the screen to revert back to its initial "read-only" state. A screen-shot of the screen in this state is shown below:

To modify data for an existing customer record, click the customer record in the list to highlight it and click the "Update" button. This will enable the fields on the bottom half of the screen. The buttons to add, update, and delete will become unavailable; the buttons to save or cancel will be available. When you are done changing the data in the fields, click the Save button, which will cause the record to be updated in the list and will cause the screen to revert back to its initial "read-only" state.

To delete a customer record, click the customer record in the list to highlight it and click the "Delete" button. The following message will be displayed:

Responding "Yes" to the confirmation prompt will cause the applciation to delete the record and remove it from the list.

To exit the Customer Maintenance screen, click the "Close" button when the screen is in its "read only" state. The Close button will not be available when you have an "add" or "update" pending. If you attempt to close the screen with the Windows "X" button while you have an "add" or "update" pending, the following message will be displayed:

Highlights of the code, as it relates to ADO, are presented below.

         Three ADO object variables (representing and ADO Connection, Command, and Recordset, respectively) are declared at the form level. This a one-form application (with a handful of supporting modules), so in this case, form-level scope is serviceable.

Private mobjConn                As ADODB.Connection
Private mobjCmd                 As ADODB.Command
Private mobjRst                 As ADODB.Recordset

         The database is opened in the "ConnectToDB" Sub.

First, the Connection object variable mobjConn is instantiated by setting it to New ADODB.Connection. Then the ConnectionString property is set. A difference between this sample application and the ones in the previous topic is that this application uses a DSN-less connection meaning that the steps we went through in the previous ADO examples to set up a DSN are NOT required here. As you may recall from the previous examples, using a DSN connection in your code requires that a DSN be set up on the computer that your program is running on. This restricts where your code can run. On the other hand, a DSN-less connection specifies all the parameters necessary to connect to the database and allows your program to be run on different machines without having to set up a new DSN.

In the case of our sample application, two parameters are required to connect to the Access database: first, the Provider parameter (which specifies Microsoft.Jet.OLEDB.4.0; and second, the Data Source parameter, which specifies the full path of the Access mdb file. In the case of this sample application, it is expected that the mdb file reside in the same folder as the VB project files, or, if this application is compiled, the database should reside in the same location as the executable (.exe) file. The application path is returned by the programmer-defined function GetAppPath (which contains the code to use the App.Path built-in function and append the backslash to it if necessary). Note that the syntax of the ConnectionString requires each parameter name to be followed by an equal sign (=) followed by the value. Each parameter name / value pair is separated by a semicolon (;). Embedded spaces in the parameter names and values are evaluated properly. For example, if your application was located in the folder "C:\My VB Apps\Database Apps", the content of the ConnectionString would be:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\My VB Apps\Database Apps\Cust.mdb"

Note: If you connect to other databases such as Oracle or SQL Server, different parameters (such as Server, UID, and PWD) will be required; however the syntax rules described above still apply.

After the ConnectionString has been set, the Open method is then used to open the connection to the database.

The Command object mobjCmd is then instantiated by setting it to New ADODB.Command. The Command object represents a command to execute against a database. Command objects are often used to create recordsets or execute action queries. A Command object must use a Connection, either by establishing its own, or by using an existing connection. To use an existing connection, set the Command object's ActiveConnection property to the open Connection object, as shown in the code below. This routine also sets the Command object's CommandType property, which tells ADO how to interpret the contents of the CommandText property (which we will be setting to SQL statements in various places in the application). Since this application will always be passing the Command object a textual SQL string, the value is set to the constant adCmdText (other possible values for CommandType include adCmdTable, which would cause the CommandText to be evaluated as a database table, and adCmdStoredProc, which would cause the CommandText to evaluated as the name of a stored procedure).

'-----------------------------------------------------------------------------
Private Sub ConnectToDB()
'-----------------------------------------------------------------------------
 
    Set mobjConn = New ADODB.Connection
    mobjConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
                              & "Data Source=" _
                              & GetAppPath _
                              & "Cust.mdb"
    mobjConn.Open
 
    Set mobjCmd = New ADODB.Command
    Set mobjCmd.ActiveConnection = mobjConn
    mobjCmd.CommandType = adCmdText
 
End Sub

         In the "LoadCustomerListView" Sub, the contents of the Customer table is loaded into the listview. First, a SQL SELECT statement is built in the String variable strSQL. The String variable strSQL is then assigned to the CommandText property of the Command object with the statement

mobjCmd.CommandText = strSQL

Following this, the Recordset object mobjRst is then populated by assigning it the result of the Execute method of the Command object in the statement

Set mobjRst = mobjCmd.Execute

Note: A Recordset object created with the Command.Execute method always creates a forward-only, read-only recordset ("firehose" cursor).

The code then loops through the recordset, populating each row of the listview. At the bottom of the Sub, the recordset object is set to Nothing, which disconnects it from the database. All manipulations of the data from the point on are handled through the listview, until it is time to update or insert a record back into the database.

It should be noted that the process of loading the entire contents of a table into a listview in this fashion works well for tables with a small number of rows you do not want to do this for recordsets containing thousands of rows.

'-----------------------------------------------------------------------------
Private Sub LoadCustomerListView()
'-----------------------------------------------------------------------------
                                
    Dim strSQL      As String
    Dim objCurrLI   As ListItem
    Dim strZip      As String
    Dim strPhone    As String
                                
    strSQL = "SELECT FirstName" _
           & "     , LastName" _
           & "     , Address" _
           & "     , City" _
           & "     , State" _
           & "     , Zip" _
           & "     , PhoneNumber" _
           & "     , CustID" _
           & "  FROM Customer " _
           & " ORDER BY LastName" _
           & "        , FirstName"
   
    mobjCmd.CommandText = strSQL
    Set mobjRst = mobjCmd.Execute
   
    lvwCustomer.ListItems.Clear
   
    With mobjRst
        Do Until .EOF
            strPhone = !PhoneNumber & ""
            If Len(strPhone) > 0 Then
                strPhone = "(" & Left$(strPhone, 3) & ") " _
                         & Mid$(strPhone, 4, 3) & "-" _
                         & Right$(strPhone, 4)
            End If
            Set objCurrLI = lvwCustomer.ListItems.Add(, , !FirstName & "", , "Custs")
            objCurrLI.SubItems(mlngCUST_LAST_IDX) = !LastName & ""
            objCurrLI.SubItems(mlngCUST_ADDR_IDX) = !Address & ""
            objCurrLI.SubItems(mlngCUST_CITY_IDX) = !City & ""
            objCurrLI.SubItems(mlngCUST_ST_IDX) = !State & ""
            objCurrLI.SubItems(mlngCUST_ZIP_IDX) = !Zip & ""
            objCurrLI.SubItems(mlngCUST_PHONE_IDX) = strPhone
            objCurrLI.SubItems(mlngCUST_ID_IDX) = CStr(!CustID)
            .MoveNext
        Loop
    End With
   
    With lvwCustomer
        If .ListItems.Count > 0 Then
            Set .SelectedItem = .ListItems(1)
            lvwCustomer_ItemClick .SelectedItem
        End If
    End With
   
    Set objCurrLI = Nothing
    Set mobjRst = Nothing
 
End Sub

         In the "cmdSave_Click" event procedure, depending on whether an add or update has been initiated, a SQL INSERT or UPDATE statement is built with the String variable strSQL. The String variable strSQL is then assigned to the CommandText property of the Command object with the statement

mobjCmd.CommandText = strSQL

The INSERT or UPDATE action query is then executed with the statement

mobjCmd.Execute

Note that the record ID plays an important role. For an add, the new record ID is obtained by calling the programmer-defined function GetNextCustID, which is described a little later below. For an update, the record ID of the currently selected item in the listview is used in the UPDATE statement to update the record. In either case, the contents of the listview is updated approriately to reflect the insert or update.

'-----------------------------------------------------------------------------
Private Sub cmdSave_Click()
'-----------------------------------------------------------------------------
 
    Dim strPhone        As String
    Dim objNewListItem  As ListItem
    Dim lngIDField      As Long
    Dim strSQL          As String
 
    If Not ValidateFormFields Then Exit Sub
   
    strPhone = txtArea.Text & txtPrfx.Text & txtLine.Text
   
    If mstrMaintMode = "ADD" Then
   
        lngIDField = GetNextCustID()
       
        strSQL = "INSERT INTO Customer(  CustID"
        strSQL = strSQL & "            , FirstName"
        strSQL = strSQL & "            , LastName"
        strSQL = strSQL & "            , Address"
        strSQL = strSQL & "            , City"
        strSQL = strSQL & "            , State"
        strSQL = strSQL & "            , Zip"
        strSQL = strSQL & "            , PhoneNumber"
        strSQL = strSQL & "         ) VALUES ("
        strSQL = strSQL & lngIDField
        strSQL = strSQL & ", '" & Replace$(txtFirst.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtLast.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtAddr.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtCity.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & txtState.Text & "'"
        strSQL = strSQL & ", '" & txtZip.Text & "'"
        strSQL = strSQL & ", '" & strPhone & "'"
        strSQL = strSQL & ")"
       
        Set objNewListItem = lvwCustomer.ListItems.Add(, , txtFirst.Text, , "Custs")
        PopulateListItem objNewListItem
        With objNewListItem
            .SubItems(mlngCUST_ID_IDX) = CStr(lngIDField)
            .EnsureVisible
        End With
        Set lvwCustomer.SelectedItem = objNewListItem
        Set objNewListItem = Nothing
    Else
        lngIDField = CLng(lvwCustomer.SelectedItem.SubItems(mlngCUST_ID_IDX))
       
        strSQL = "UPDATE Customer SET "
        strSQL = strSQL & "  FirstName   = '" & Replace$(txtFirst.Text, "'", "''") & "'"
        strSQL = strSQL & ", LastName    = '" & Replace$(txtLast.Text, "'", "''") & "'"
        strSQL = strSQL & ", Address     = '" & Replace$(txtAddr.Text, "'", "''") & "'"
        strSQL = strSQL & ", City        = '" & Replace$(txtCity.Text, "'", "''") & "'"
        strSQL = strSQL & ", State       = '" & txtState.Text & "'"
        strSQL = strSQL & ", Zip         = '" & txtZip.Text & "'"
        strSQL = strSQL & ", PhoneNumber = '" & strPhone & "'"
        strSQL = strSQL & " WHERE CustID = " & lngIDField
       
        lvwCustomer.SelectedItem.Text = txtFirst.Text
        PopulateListItem lvwCustomer.SelectedItem
    End If
   
    mobjCmd.CommandText = strSQL
    mobjCmd.Execute
   
    SetFormState True
 
    mblnUpdateInProgress = False
 
End Sub

         When we need to add a new record, a new, unique record ID must generated. In this particular sample application, the record ID is defined as a Long Integer in the database. The GetNextCustID function shown below uses the SQL MAX function to find the highest existing value for the CustID field, adds one to it, and returns that value to the caller. It should be noted that if the CustID field was defined as an Access AutoNumber field, the logic of this application would have to be modified accordingly.

'-----------------------------------------------------------------------------
Private Sub cmdSave_Click()
'-----------------------------------------------------------------------------
 
    Dim strPhone        As String
    Dim objNewListItem  As ListItem
    Dim lngIDField      As Long
    Dim strSQL          As String
 
    If Not ValidateFormFields Then Exit Sub
   
    strPhone = txtArea.Text & txtPrfx.Text & txtLine.Text
   
    If mstrMaintMode = "ADD" Then
   
        lngIDField = GetNextCustID()
       
        strSQL = "INSERT INTO Customer(  CustID"
        strSQL = strSQL & "            , FirstName"
        strSQL = strSQL & "            , LastName"
        strSQL = strSQL & "            , Address"
        strSQL = strSQL & "            , City"
        strSQL = strSQL & "            , State"
        strSQL = strSQL & "            , Zip"
        strSQL = strSQL & "            , PhoneNumber"
        strSQL = strSQL & "         ) VALUES ("
        strSQL = strSQL & lngIDField
        strSQL = strSQL & ", '" & Replace$(txtFirst.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtLast.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtAddr.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtCity.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & txtState.Text & "'"
        strSQL = strSQL & ", '" & txtZip.Text & "'"
        strSQL = strSQL & ", '" & strPhone & "'"
        strSQL = strSQL & ")"
       
        Set objNewListItem = lvwCustomer.ListItems.Add(, , txtFirst.Text, , "Custs")
        PopulateListItem objNewListItem
        With objNewListItem
            .SubItems(mlngCUST_ID_IDX) = CStr(lngIDField)
            .EnsureVisible
        End With
        Set lvwCustomer.SelectedItem = objNewListItem
        Set objNewListItem = Nothing
    Else
        lngIDField = CLng(lvwCustomer.SelectedItem.SubItems(mlngCUST_ID_IDX))
       
        strSQL = "UPDATE Customer SET "
        strSQL = strSQL & "  FirstName   = '" & Replace$(txtFirst.Text, "'", "''") & "'"
        strSQL = strSQL & ", LastName    = '" & Replace$(txtLast.Text, "'", "''") & "'"
        strSQL = strSQL & ", Address     = '" & Replace$(txtAddr.Text, "'", "''") & "'"
        strSQL = strSQL & ", City        = '" & Replace$(txtCity.Text, "'", "''") & "'"
        strSQL = strSQL & ", State       = '" & txtState.Text & "'"
        strSQL = strSQL & ", Zip         = '" & txtZip.Text & "'"
        strSQL = strSQL & ", PhoneNumber = '" & strPhone & "'"
        strSQL = strSQL & " WHERE CustID = " & lngIDField
       
        lvwCustomer.SelectedItem.Text = txtFirst.Text
        PopulateListItem lvwCustomer.SelectedItem
    End If
   
    mobjCmd.CommandText = strSQL
    mobjCmd.Execute
   
    SetFormState True
 
    mblnUpdateInProgress = False
 
End Sub

         For a delete action, after we have confirmed that the user truly wants to delete the record, we set the CommandText property of the Command object directly with the necessary SQL statement as shown below:

mobjCmd.CommandText = "DELETE FROM Customer WHERE CustID = " & lngCustID

The DELETE action query is then executed with the statement

mobjCmd.Execute

Logic is then executed to update the listview to remove the deleted record.

'-----------------------------------------------------------------------------
Private Sub cmdDelete_Click()
'-----------------------------------------------------------------------------
 
    Dim strFirstName    As String
    Dim strLastName     As String
    Dim lngCustID       As Long
    Dim lngNewSelIndex  As Long
   
    If lvwCustomer.SelectedItem Is Nothing Then
        MsgBox "No Customer selected to delete.", _
               vbExclamation, _
               "Delete"
        Exit Sub
    End If
   
    With lvwCustomer.SelectedItem
        strFirstName = .Text
        strLastName = .SubItems(mlngCUST_LAST_IDX)
        lngCustID = CLng(.SubItems(mlngCUST_ID_IDX))
    End With
   
    If MsgBox("Are you sure that you want to delete Customer '" _
            & strFirstName & " " & strLastName & "'?", _
              vbYesNo + vbQuestion, _
              "Confirm Delete") = vbNo Then
        Exit Sub
    End If
   
    mobjCmd.CommandText = "DELETE FROM Customer WHERE CustID = " & lngCustID
    mobjCmd.Execute
   
    With lvwCustomer
        If .SelectedItem.Index = .ListItems.Count Then
            lngNewSelIndex = .ListItems.Count - 1
        Else
            lngNewSelIndex = .SelectedItem.Index
        End If
        .ListItems.Remove .SelectedItem.Index
        If .ListItems.Count > 0 Then
            Set .SelectedItem = .ListItems(lngNewSelIndex)
            lvwCustomer_ItemClick .SelectedItem
        Else
            ClearCurrRecControls
        End If
    End With
 
End Sub

         When the program ends, the DisconnectFromDB sub is called to clean up the database objects. The Command object variable mobjCmd is set to Nothing. The ADO Connection is then closed by issuing the Close method on the Connection object variable mobjConn, and then that object is set to Nothing as well. Note: It was not necessary to "clean up" the Recordset object variable mobjRst, because it was set to Nothing at the end of each Sub in which it was used.

'-----------------------------------------------------------------------------
Private Sub DisconnectFromDB()
'-----------------------------------------------------------------------------
 
    Set mobjCmd = Nothing
   
    mobjConn.Close
    Set mobjConn = Nothing
 
End Sub

Using the ListView Control

In this section of the article, code related to the use of the ListView will be explained. To incorporate the ListView control into your project, you must add the Microsoft Windows Common Controls 6.0 component group to your toolbox (via Project -> Components). This is the same group that includes the ImageList, Toolbar, StatusBar, etc.

In this project, a ListView control named lvwCustomer and an ImageList control named imlLVIcons were added to the form. (If you want to use icons with your ListView, you must store those icons in an ImageList control that will be tied to the ListView control.) An icon representing "customers" was added to the imlLVIcons ImageList; this image was given a Key property of "Custs".

         The following properties of the ListView were set at design time:

Property

Value

Notes

View

3 lvwReport

The ListView is used prominently in the MS-Windows interface. It is used to display the lists of files and folders in the Windows Explorer and My Computer applications. In those applications, you can go to the View menu and specify Large Icons, Small Icons, List, or Details, and the appearance of the file list is modified accordingly. With the VB ListView control, the 0-lvwIcon (the default), 1-lvwSmallIcon, 2-lvwList, and 3-lvwReport settings for the View property correspond respectively to the Windows Explorer / My Computer View menu options listed above. Setting the ListView View property to 3-lvwReport enables the display of data in a columnar, grid-like fashion.

LabelEdit

1 - lvwManual

In a Windows Explorer or My Computer ListView, you know that you can rename a file by clicking once on its text label, then clicking it again. With the VB ListView control, the editing of the text label is possible when the LabelEdit property is set to 0-lvwAutomatic (which is the default). To prevent the user from modifying the data in the text label (which is the first column of the list when using the 3-lvwReport View), the LabelEdit property must be set to 1-lvwManual.

FullRowSelect

True

This is a Boolean property that is applicable only when View is set to 3-lvwReport. If False (the default), only the first column will be highlighted when a row is selected. If True, the entire row will be highlighted when selected.

GridLines

True

This is a Boolean property that is applicable only when View is set to 3-lvwReport. If True, grid lines will border the cells of the ListView. The default is False.

On the Property Pages, Image Lists tab, the "Small" Icon Image List was set to imlLVIcons (the ImageList that was added to the form).

         In the Form_Load event, a call is made to the programmer-defined Sub "SetupCustLVCols". Here, we set up the columns for the ListView by using the Add method of the ListView's ColumnHeaders collection. The arguments for the Add method, all optional, are: index, key, text, width, alignment, icon. In the code below, only the text and the width arguments are specified. The text argument specifies the text that will appears in the column header. A common technique to specify the width is to use a percentage of the ListView as a whole. In the code below, the First Name will take up 15% of the ListView's width; the Last Name will take up 12%, and so on. In order to prevent a horizontal scroll bar from appearing at the bottom of the ListView, keep the total width under 100% (in the code below, the percentages add up to 98%). (If you want to display many columns, or certain columns must be particularly wide, the total percentage can certainly exceed 100%, in which case a horizontal scroll bar will automatically appear at the bottom of the ListView, and the user will have to scroll to see one or more columns.) Note that you may specify 0 for the column width, in which case you create a "hidden" column, useful for storing data that the user need not see (in this case, the "ID" column). The alignment property is not specified for any of the columns in the code below, so by default, all of the columns will be left-aligned. The other alignment options are centered or right-aligned. The alignment argument for left, center, and right are specified with the constants lvwColumnLeft, lvwColumnCenter, and lvwColumnRight, respectively. The code for this Sub is as follows:

'-----------------------------------------------------------------------------
Private Sub SetupCustLVCols()
'-----------------------------------------------------------------------------
                                
    With lvwCustomer
        .ColumnHeaders.Clear
        .ColumnHeaders.Add , , "First Name", .Width * 0.15
        .ColumnHeaders.Add , , "Last Name", .Width * 0.12
        .ColumnHeaders.Add , , "Address", .Width * 0.2
        .ColumnHeaders.Add , , "City", .Width * 0.15
        .ColumnHeaders.Add , , "St", .Width * 0.06
        .ColumnHeaders.Add , , "Zip", .Width * 0.1
        .ColumnHeaders.Add , , "Phone #", .Width * 0.2
        .ColumnHeaders.Add , , "ID", 0
    End With
 
End Sub

         Also in the Form_Load event, following the call to "SetupCustLVCols" is the call to the "LoadCustomerListView" Sub. We looked at this Sub earlier to examine the ADO/database aspects of the code; now we will look at it to examine the ListView aspects of the code.

A local ListItem object, objCurrLI, is declared. ListItem objects represent the entries of the ListView; they are the components of the ListView's ListItems collection.

After the recordset has been created, we first use the Clear method to remove all existing ListItem objects from the ListView (this step is technically not needed in the case of this particular application, but it is good practice to do this there could be situations where you need to reload a ListView, and failure to clear the existing items will result in extraneous or duplicate items in the list).

As we loop through the Recordset, for each record we create a new ListItem object by invoking the Add method of the ListItems collection, setting the reference to the new ListItem to the objCurrLI variable. The arguments for the Add method, all optional, are: index, key, text, icon, smallicon. We are using only the text and the smallicon arguments. The text argument sets the Text property of the ListView; it is the text that will appear in the first column of the ListView (in this case, it is the FirstName field from the recordset). The smallicon argument refers to the image that will appear to the left of each ListItem; here we specify "Custs", which is the Key of the desired image in the imlLVIcons ImageList control (which we tied to this ListView control).

The remaining fields of the recordset are assigned to the corresponding SubItems entries of the current ListItem. Whenever you add more than one ColumnHeader object, you create corresponding SubItem elements that are associated with each ListItem. The SubItems collection is a string array of data associated with a ListItem. ColumnHeaders and SubItems are "1-based" collections however, the upper bound of the SubItems is always one greater than the upper bound of the ColumnHeaders. This is because ColumnHeaders(1) corresponds to the ListItem's Text property; ColumnHeaders(2) through ColumnHeaders(n) correspond to the ListItem's SubItems(1) through SubItems(n 1). Note that constants are used for the SubItem indexes (you could alternatively just use hard-coded numbers to refer to the indexes). These constants were defined at the form-level: 

' Customer LV SubItem Indexes ...
Private Const mlngCUST_LAST_IDX          As Long = 1
Private Const mlngCUST_ADDR_IDX          As Long = 2
Private Const mlngCUST_CITY_IDX          As Long = 3
Private Const mlngCUST_ST_IDX            As Long = 4
Private Const mlngCUST_ZIP_IDX           As Long = 5
Private Const mlngCUST_PHONE_IDX         As Long = 6
Private Const mlngCUST_ID_IDX            As Long = 7

After the loop has completed, we then check the Count property of the ListItems collection. As long as at least one record was loaded, we set the SelectedItem property of the ListView to the first ListItem. The SelectedItem property of the ListView is a reference to the ListItem that is currently selected. (Normally, the SelectedItem property is set when the user clicks on a ListItem.) We then call the ListView's ItemClick event (lvwCustomer_ItemClick). The ItemClick event expects a ListItem argument, so we pass it the selected item that we just set. (Normally, the ItemClick event is fired when the user clicks on a ListItem.) We will explore the code for the lvwCustomer_ItemClick event shortly.

The code for "LoadCustomerListView" is shown below, with the ListView-related code in bold:

'-----------------------------------------------------------------------------
Private Sub LoadCustomerListView()
'-----------------------------------------------------------------------------
                                
    Dim strSQL      As String
    Dim objCurrLI   As ListItem
    Dim strZip      As String
    Dim strPhone    As String
                                
    strSQL = "SELECT FirstName" _
           & "     , LastName" _
           & "     , Address" _
           & "     , City" _
           & "     , State" _
           & "     , Zip" _
           & "     , PhoneNumber" _
           & "     , CustID" _
           & "  FROM Customer " _
           & " ORDER BY LastName" _
           & "        , FirstName"
   
    mobjCmd.CommandText = strSQL
    Set mobjRst = mobjCmd.Execute
   
    lvwCustomer.ListItems.Clear
   
    With mobjRst
        Do Until .EOF
            strPhone = !PhoneNumber & ""
            If Len(strPhone) > 0 Then
                strPhone = "(" & Left$(strPhone, 3) & ") " _
                         & Mid$(strPhone, 4, 3) & "-" _
                         & Right$(strPhone, 4)
            End If
            Set objCurrLI = lvwCustomer.ListItems.Add(, , !FirstName & "", , "Custs")
            objCurrLI.SubItems(mlngCUST_LAST_IDX) = !LastName & ""
            objCurrLI.SubItems(mlngCUST_ADDR_IDX) = !Address & ""
            objCurrLI.SubItems(mlngCUST_CITY_IDX) = !City & ""
            objCurrLI.SubItems(mlngCUST_ST_IDX) = !State & ""
            objCurrLI.SubItems(mlngCUST_ZIP_IDX) = !Zip & ""
            objCurrLI.SubItems(mlngCUST_PHONE_IDX) = strPhone
            objCurrLI.SubItems(mlngCUST_ID_IDX) = CStr(!CustID)
            .MoveNext
        Loop
    End With
   
    With lvwCustomer
        If .ListItems.Count > 0 Then
            Set .SelectedItem = .ListItems(1)
            lvwCustomer_ItemClick .SelectedItem
        End If
    End With
   
    Set objCurrLI = Nothing
    Set mobjRst = Nothing
 
End Sub

         The ListView's ItemClick event is fired when the user clicks on a ListItem in the ListView. VB passes an argument called Item to the event, which refers to the ListItem that was clicked. In the lvwCustomer_ItemClick event below, we populate the textboxes in the "Current Record" frame of the form with the data from the currently selected ListItem.

'-----------------------------------------------------------------------------
Private Sub lvwCustomer_ItemClick(ByVal Item As MSComctlLib.ListItem)
'-----------------------------------------------------------------------------
 
    gblnPopulating = True
   
    With Item
        txtFirst.Text = .Text
        txtLast.Text = .SubItems(mlngCUST_LAST_IDX)
        txtAddr.Text = .SubItems(mlngCUST_ADDR_IDX)
        txtCity.Text = .SubItems(mlngCUST_CITY_IDX)
        txtState.Text = .SubItems(mlngCUST_ST_IDX)
        txtZip.Text = .SubItems(mlngCUST_ZIP_IDX)
        If .SubItems(mlngCUST_PHONE_IDX) = "" Then
            txtArea.Text = ""
            txtPrfx.Text = ""
            txtLine.Text = ""
        Else
            txtArea.Text = Mid$(.SubItems(mlngCUST_PHONE_IDX), 2, 3)
            txtPrfx.Text = Mid$(.SubItems(mlngCUST_PHONE_IDX), 7, 3)
            txtLine.Text = Right$(.SubItems(mlngCUST_PHONE_IDX), 4)
        End If
    End With
   
    gblnPopulating = False
   
End Sub

         The ListView's ColumnClick event is fired when the user clicks on one of the ListView's column headers. VB passes an argument called ColumnHeader to the event, which refers to the column header that was clicked. What we want to do is sort the ListView by the column that was clicked. The ListView control has three properties related to sorting:

Sorted is a Boolean indicating whether or not the ListView is currently sorted.

SortKey is an integer representing the column currently sorted. Zero specifies that the ListView is sorted on the value of the Text property (i.e., the first column). A number from 1 to the number of SubItems specifies that the ListView is sorted on the value of that SubItem. The SubItemIndex property of the ColumnHeader object returns the appropriate value.

SortOrder is a numeric value indicating whether the sort is ascending or descending. The values can be specified with the constants lvwAscending or lvwDescending.

The first part of the code in the lvwCustomer_ColumnClick event checks to see if the user clicked on the column that the ListView is currently sorted on. If so, it toggles the ascending / descending value. Otherwise, it sorts the ListView on the clicked column in ascending order. The second part of the code makes sure that, if an item was selected prior to the sort, it is still visible after the sort. The EnsureVisible method of the ListItem object checks that the ListItem is currently viewable in the ListView if not, it automatically scrolls the ListView to make it viewable.

'-------------------------------------------------------------------------
Private Sub lvwCustomer_ColumnClick(ByVal ColumnHeader As SComctlLib.ColumnHeader)
'-------------------------------------------------------------------------
   
    ' sort the listview on the column clicked
    With lvwCustomer
        If (.Sorted) And (ColumnHeader.SubItemIndex = .SortKey) Then
            If .SortOrder = lvwAscending Then
                .SortOrder = lvwDescending
            Else
                .SortOrder = lvwAscending
            End If
        Else
            .Sorted = True
            .SortKey = ColumnHeader.SubItemIndex
            .SortOrder = lvwAscending
        End If
        .Refresh
    End With
       
    ' If an item was selected prior to the sort,
    ' make sure it is still visible now that the sort is done.
    If Not lvwCustomer.SelectedItem Is Nothing Then
        lvwCustomer.SelectedItem.EnsureVisible
    End If
 
End Sub

         Next, we will look at the ListView's role in cmdSave_Click event. We looked at this Sub earlier to examine the ADO/database aspects of the code; now we will look at it to examine the ListView aspects of the code.

A ListItem object variable, objNewListItem, is declared at the local level. This will be used on the "ADD" side (i.e., if we are saving a newly added record). On the "ADD" side, after we have set up the SQL to do an INSERT, we use the Add method of the ListItems collection to add a new ListItem. The reference to the new ListItem is assigned to the objNewListItem variable. Note that the first name that has been entered into the txtFirst textbox is used for the Text property of the newly added item. The next statement calls the programmer-defined Sub PopulateListItem, passing it the newly added ListItem as an argument (the code for PopulateListItem will be shown a little later below, but all it does is assign the values of the textboxes used in the add or update to the corresponding SubItems of the ListItem object passed in to the Sub). Following this, the new Customer ID (that was established when GetNextCustID was called) is assigned to the corresponding SubItem of the new ListItem. The EnsureVisible method is invoked to ensure that the user can see the newly added item. The SelectedItem property is then set to reference the newly added item. To clean things up, the objNewListItem variable is then set to Nothing.

On the "UPDATE" side, our job is to modify the SubItem values of the currently selected item to reflect the user's changes. Here, we get the value for the lngIDField variable from the "hidden" Cust ID column of the currently selected ListItem of the ListView. This variable is then used in the building of the UPDATE SQL statement. We then set the Text property of the currently selected item to the first name entered in the txtFirst textbox, and then we call the PopulateListItem Sub, passing the the currently selected ListItem.

The code for the "cmdSave_Click" event procedure is shown below, with the ListView-related code in bold:

'-----------------------------------------------------------------------------
Private Sub cmdSave_Click()
'-----------------------------------------------------------------------------
 
    Dim strPhone        As String
    Dim objNewListItem  As ListItem
    Dim lngIDField      As Long
    Dim strSQL          As String
 
    If Not ValidateFormFields Then Exit Sub
   
    strPhone = txtArea.Text & txtPrfx.Text & txtLine.Text
   
    If mstrMaintMode = "ADD" Then
   
        lngIDField = GetNextCustID()
       
        strSQL = "INSERT INTO Customer(  CustID"
        strSQL = strSQL & "            , FirstName"
        strSQL = strSQL & "            , LastName"
        strSQL = strSQL & "            , Address"
        strSQL = strSQL & "            , City"
        strSQL = strSQL & "            , State"
        strSQL = strSQL & "            , Zip"
        strSQL = strSQL & "            , PhoneNumber"
        strSQL = strSQL & "         ) VALUES ("
        strSQL = strSQL & lngIDField
        strSQL = strSQL & ", '" & Replace$(txtFirst.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtLast.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtAddr.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & Replace$(txtCity.Text, "'", "''") & "'"
        strSQL = strSQL & ", '" & txtState.Text & "'"
        strSQL = strSQL & ", '" & txtZip.Text & "'"
        strSQL = strSQL & ", '" & strPhone & "'"
        strSQL = strSQL & ")"
       
        Set objNewListItem = lvwCustomer.ListItems.Add(, , txtFirst.Text, , Custs")
        PopulateListItem objNewListItem
        With objNewListItem
            .SubItems(mlngCUST_ID_IDX) = CStr(lngIDField)
            .EnsureVisible
        End With
        Set lvwCustomer.SelectedItem = objNewListItem
        Set objNewListItem = Nothing
    Else
        lngIDField = CLng(lvwCustomer.SelectedItem.SubItems(mlngCUST_ID_IDX))
       
        strSQL = "UPDATE Customer SET "
        strSQL = strSQL & "  FirstName   = '" & Replace$(txtFirst.Text, "'", ''") & "'"
        strSQL = strSQL & ", LastName    = '" & Replace$(txtLast.Text, "'", ''") & "'"
        strSQL = strSQL & ", Address     = '" & Replace$(txtAddr.Text, "'", ''") & "'"
        strSQL = strSQL & ", City        = '" & Replace$(txtCity.Text, "'", ''") & "'"
        strSQL = strSQL & ", State       = '" & txtState.Text & "'"
        strSQL = strSQL & ", Zip         = '" & txtZip.Text & "'"
        strSQL = strSQL & ", PhoneNumber = '" & strPhone & "'"
        strSQL = strSQL & " WHERE CustID = " & lngIDField
       
        lvwCustomer.SelectedItem.Text = txtFirst.Text
        PopulateListItem lvwCustomer.SelectedItem
    End If
   
    mobjCmd.CommandText = strSQL
    mobjCmd.Execute
   
    SetFormState True
 
    mblnUpdateInProgress = False
 
End Sub

         The code for the programmer-defined Sub "PopulateListItem" (discussed above) is shown below:

'-----------------------------------------------------------------------------
Private Sub PopulateListItem(pobjListItem As ListItem)
'-----------------------------------------------------------------------------
 
    With pobjListItem
        .SubItems(mlngCUST_LAST_IDX) = txtLast.Text
        .SubItems(mlngCUST_ADDR_IDX) = txtAddr.Text
        .SubItems(mlngCUST_CITY_IDX) = txtCity.Text
        .SubItems(mlngCUST_ST_IDX) = txtState.Text
        .SubItems(mlngCUST_ZIP_IDX) = txtZip.Text
        .SubItems(mlngCUST_PHONE_IDX) _
            = IIf(txtArea.Text = "", _
                  "", _
                  "(" & txtArea.Text & ") " & txtPrfx.Text & "-" & txtLine.Text)
 
    End With
 
End Sub

         The last bit of ListView-related code we will look at is in the cmdDelete_Click event procedure. In the first section of highlighted code, we use the SelectedItem to get the first and last name of the customer to be deleted so that we can present the message "Are you sure that you want to delete Customer so-and-so?"; we also get the Cust ID for use in building the SQL string. Provided that the user goes ahead with the delete, we must refresh the ListView accordingly: we are going to remove the currently selected item, and we also want to establish a "new" selected item (we will store the index of the new selected item in the variable lngNewSelIndex). We first test to see if the item to be deleted is the last item of the ListView if it is, then the "new" selected item's index will be one less than currently selected item's index (for example, if you have five items and you delete the fifth one, the "new" last item will be the fourth one) otherwise the "new" selected item's index will be the same as the currently selected item's index (for example, if you have five items and you delete the third one, the item that was previously fourth will now be third). The selected item is then removed with the Remove method of the ListItems collection. Provided that we did not delete the very last record of the table, we set the "new" selected item (using the value of the lngNewSelIndex variable) and then call the lvwCustomer_ItemClick event procedure, passing it that new item which will cause the textboxes to be populated with the data from the newly selected item.

'-----------------------------------------------------------------------------
Private Sub cmdDelete_Click()
'-----------------------------------------------------------------------------
 
    Dim strFirstName    As String
    Dim strLastName     As String
    Dim lngCustID       As Long
    Dim lngNewSelIndex  As Long
   
    If lvwCustomer.SelectedItem Is Nothing Then
        MsgBox "No Customer selected to delete.", _
               vbExclamation, _
               "Delete"
        Exit Sub
    End If
   
    With lvwCustomer.SelectedItem
        strFirstName = .Text
        strLastName = .SubItems(mlngCUST_LAST_IDX)
        lngCustID = CLng(.SubItems(mlngCUST_ID_IDX))
    End With
   
    If MsgBox("Are you sure that you want to delete Customer '" _
            & strFirstName & " " & strLastName & "'?", _
              vbYesNo + vbQuestion, _
              "Confirm Delete") = vbNo Then
        Exit Sub
    End If
   
    mobjCmd.CommandText = "DELETE FROM Customer WHERE CustID = " & lngCustID
    mobjCmd.Execute
   
    With lvwCustomer
        If .SelectedItem.Index = .ListItems.Count Then
            lngNewSelIndex = .ListItems.Count - 1
        Else
            lngNewSelIndex = .SelectedItem.Index
        End If
        .ListItems.Remove .SelectedItem.Index
        If .ListItems.Count > 0 Then
            Set .SelectedItem = .ListItems(lngNewSelIndex)
            lvwCustomer_ItemClick .SelectedItem
        Else
            ClearCurrRecControls
        End If
    End With
 
End Sub

Download the project files for this sample application here.

If you enjoyed this post, subscribe for updates (it's free)

Big thanks for this tutorial.

Big thanks for this tutorial. It was a big help!

Many thanks

The sample helped me quite a lot.
Thank you very much
Sandro (Italy)

Help pls

hi sir,

I just want to know how to print that list view items and how to filter some list view items?

thanks dude,,

your works are awesome., it helps me a lot..

How to make datagrid editable.

how to make the data grid editable like enter new data from the data grid and stores it into the database access.

How to make datagrid editable.

how to make the datagrid editable like enter new data from the datagrid and stores it into the database access.

show listbox when an item is added in the textbox.

How to show a list box when an item is written in the textbox by a user and that item is already present in that list box, it is like a google suggestion or like an intellisense.
Kindly reply me as soon as u can i want to do my project complte quickly.
Thanks

plz give coding so that i cn

plz give coding so that i cn access data base by command button
sSERACH BY NAME OR ACCOUNT NO.

ab8 table

how to make search for the names in above table. whats the programme for this

Excellent Work & plz send me sale form

hi, I'm beginner in vb6, plz help me.i make stock control project in my exam,but i have a problem.Ur customer form is best.because if u can send list view or DBgrid, amount ,quantity and discount with made sale form like customer form. my English poor.sorry.
my mail: moneydami@ymail.com.

i'm just a beginner in vb6.

i'm just a beginner in vb6. pls. help me in database connection... i will br so greatefull...

D.A

trouble shoot this error,,please,,

I had one probleme to learn about VB 6,
here are the list of the code, how to make good trouble shoot
yellow line in VB = (==>)
--------------------------------------------------------------
run time error '91'
object variable or with block variable not set"
Private Sub cbopro_Click(Area As Integer)
===================================
Private Sub cbopro_Click(Area As Integer)
rstbproduk.Requery
==> If Area = 2 Then Call lCarikdproduk
End Sub

Private Sub lCarikdproduk()
If Trim(cbopro.Text) = "" Then Exit Sub
Set rsDetail = New ADODB.Recordset
With rsDetail
sql = "SELECT * from tbproduk WHERE kdproduk = '" & cbopro.Text & "'"
.Open sql, conn, adOpenStatic, adLockReadOnly
If .RecordCount = 0 Then
lblkdproduk.Caption = ""
Else
'cnmproduk = !nmproduk
lblkdproduk.Caption = !nmproduk
End If
End With
End Sub

I need your help soon,,,
thanks a lot for your time,,

how to search a data from database

I am just beginer in vb6. I want to design a form for searching data of book with Accession No.
If anyone send me source code of the program. I really will be grateful.
Thanks
umesh

I want to create AIRLINES

I want to create AIRLINES project using my own knowledge. If you do any help for me

Hello Sir, Hoe generate

Hello Sir,

Hoe generate dynamic report(Using any Reporting Tool) so that client can modify it

thanks

Reports

Dear Sir,

How to generate dynamic reports (using any Reporting Tool) so that customer can modify it. Please guide me on this.

Thanks

I want to learn ado shape

Dear Sir,
I want to learn ado shape .How to add , delete,modify record in ado shape?
Thanks

listview problem in deleting items

when we are selecting any record from listview and pressing delete button it doesn't delete the selected record from the database,it deletes the first record present in the database not the selected...plz help it out

thanks

listview problem in deleting items

here is the code..hope it will help..
lvw - listview name
cDel - name of commandbutton.

If lvw.ListItems.Count <> 0 Then
lvw.Tag = lvw.ListItems(lvw.SelectedItem.Index)
End If

Private Sub cDel_Click()
If lvw.Tag <> "" Then
If MsgBox("Are you sure you want to DELETE this record?", vbExclamation + vbYesNo, "Delete Record") = vbYes Then
con.Execute "Delete from tblcourse where cId = " & Int(lvw.Tag) & ""
MsgBox "Data Successfully Deleted.", vbInformation, "Delete"
Call Lvw_Loader();lvw.tag=""
Else: lvw.Tag = ""
End If
Else: MsgBox "NO selected record to be Deleted.", vbExclamation, "Delete Record"
End If
End Sub

error while cancelling the add person

i love your code very good ..but there is a problem
i ereased all the contacts in the list view
and when i add person and whant to cancel i get error
-------------------------
run time error 91
object variable or with block variable not set
------------------------
any solution??

the samething

i get the same error to..
somebody can help us?

One solution found!

Yeap! Same error to me also... The problem is at the Private Sub lvwCustomer_ItemClick. Replace the sub with the following one:
'-----------------------------------------------------------------------------
Private Sub lvwCustomer_ItemClick(ByVal Item As MSComctlLib.ListItem)
'-----------------------------------------------------------------------------

gblnPopulating = True

If Not Item Is Nothing Then

With Item
txtFirst.Text = .Text
txtLast.Text = .SubItems(mlngCUST_LAST_IDX)
txtAddr.Text = .SubItems(mlngCUST_ADDR_IDX)
txtCity.Text = .SubItems(mlngCUST_CITY_IDX)
txtState.Text = .SubItems(mlngCUST_ST_IDX)
txtZip.Text = .SubItems(mlngCUST_ZIP_IDX)
If .SubItems(mlngCUST_PHONE_IDX) = "" Then
txtArea.Text = ""
txtPrfx.Text = ""
txtLine.Text = ""
Else
txtArea.Text = Mid$(.SubItems(mlngCUST_PHONE_IDX), 2, 3)
txtPrfx.Text = Mid$(.SubItems(mlngCUST_PHONE_IDX), 7, 3)
txtLine.Text = Right$(.SubItems(mlngCUST_PHONE_IDX), 4)
End If
End With
End If

gblnPopulating = False

End Sub

It works perfectly now. The code was trying to display the data of the item clicked! But all the records were deleted so no display data was found. The If statement solved the problem!

progressbar loading DB

Hello everyone
i need help
i made a programm with database access using listview and a progressbar that will count the records and display them in the progressbar
and its not working.
this is the code.
Option Explicit
Public Cn As ADODB.Connection
Public RS As ADODB.Recordset

Private Sub Form_Load()
Set RS = Cn.Execute("select * from tblAddresses ")
While Not RS.EOF
Set itm = frmMain.lvwAddress.ListItems.Add(, , RS!FirstName)
RS.MoveNext
pbr.Value = pbr.Value + 1
Wend
frmMain.Show
End Sub

DoEvents

Under the line "pbr.Value = pbr.Value + 1" add the following command:

DoEvents

Of course this command will slow very much the loading proccess but it is very fancy to see a progress bar and helps the user to check if everything is OK.

I believe this command is the missing part of your code.

ChrisGT7

thank you now i have another

thank you
now i have another question
i created another form in the same project as this customer listview.
now how can i show the people from this form (listview)
in my other form using combo box?
i just want to display this customer list in a nother form and to add them their from the list and the person that i choose to add.
thanks for advanced

Questions...

If I understand right, you have one combo box in your new form and this combo should be filled with all the first names of costumers? So you can choose from this combo the customer and display his details to another combos or text boxes?

Or every time you click on a customer from the list, the combo box will be filled with all the details of the selected costumer?

Looking forward for your explainations in order to help you.

combobox

hi
exactly what you said before
this:
---------------------
"you have one combo box in your new form and this combo should be filled with all the first names of costumers? So you can choose from this combo the customer and display his details to another combos or text boxes?"
i want to display the detail of the customers in the text box.

Arik

i want to show the customers in another form using combobox and displaying the data in the text

Done!

Let's say your new form is Form1, the combo for customers Combo1 and a control array of 5 text boxes to display in each one all the reamining details of the chosen customer from the combo box. Change the Index property of each text box to: 2, 3, 4, 5 and 6.
Here are the steps of the code in your new form:

Private Sub Form_Load()

For i = 1 To frmCustMaint.lvwCustomer.ListItems.Count
Combo1.AddItem frmCustMaint.lvwCustomer.ListItems(i) & " " & frmCustMaint.lvwCustomer.ListItems(i).SubItems(1)
Next
Combo1.Text = Combo1.List(0)

End Sub

Private Sub Combo1_Click()

For i = 2 To 6
Text1(i).Text = frmCustMaint.lvwCustomer.ListItems(Combo1.ListIndex + 1).SubItems(i)
Next

End Sub

If you delete a customer while your new form is open, your combo will not be updated and when you choose the deleted customer from it there will be a run-time error. You have to close your form and open it again to avoid the run-time error. Or you have to copy the code for filling the combo box in the code of the delete button.

For anything else, please ask me. I hope this sample will satisfy you!

Combobox

hey ChrisGT7
im kind of new in vb 6 first of all
second
it dosnt work and it dosnt even give me an error or something else
ill try to make it simple that you can help me.i know im doing something wrong
this is the code of my first form(forget the customers form for now)
---------------------------------------------------------------------------------------------
Option Explicit
Private lBegin As Long
Dim Columns As Long
Dim i As Long
Private fFreeze As Boolean
Private Sub abc_Click()
Form4414.Show 1
End Sub

Private Sub cmdAdd_Click()
frmNew.Show 1
End Sub

Private Sub cmdDelete_Click()
Dim strFirstName As String
If Me.ListView.ListItems.Count = 0 Then
MsgBox "", vbInformation, ""
Exit Sub
End If

If MsgBox("DELTE?", vbYesNo, " ") = vbYes Then

Call dbConnect
conn.Execute "Delete * from tbl_info where id_info=" & Val(Me.ListView.SelectedItem.Text) & ""
conn.Close
Set conn = Nothing
Me.ListView.ListItems.Remove (Me.ListView.SelectedItem.Index)
MsgBox "", vbInformation, ""
Else
cancel = True
End If

End Sub

Private Sub cmdEdit_Click()
If Me.ListView.ListItems.Count = 0 Then
MsgBox "", vbInformation, ""
Exit Sub
End If
frmEdit.Show 1

End Sub

Private Sub cmdRefresh_Click()

Text1.Text = ""

Call loadRecords
Form11.Enabled = True

End Sub

Private Sub cmdSearch_Click()

End Sub

Private Sub Form_Load()
fFreeze = True

Me.MousePointer = vbHourglass

Label8.Caption = " " & FormatDateTime(Now, vbLongDate)
Call loadRecords

With ListView
Columns = .ColumnHeaders.Count

For i = 1 To Columns
.ColumnHeaders(i).Position = Columns - i + 1
Next
End With
Me.MousePointer = vbDefault

End Sub

Private Sub Form_Unload(cancel As Integer)
Dim Form As Form

For Each Form In Forms
Unload Form
DoEvents
Next
End Sub

Private Sub lvButtons_H1_Click()
frmMain525.Show 1

End Sub

Private Sub lvButtons_H2_Click()
frmCustMaint.Show 1

End Sub

Private Sub lvButtons_H3_Click()
frmBackupDba.Show 1

End Sub

Private Sub InitSearchListVw(LV As ListView)

On Error GoTo InitErr
Dim lItem As Long
Dim lSubitem As Long

For lItem = 1 To LV.ListItems.Count
For lSubitem = 0 To LV.ColumnHeaders.Count - 1

If lSubitem = 0 Then

LV.ListItems(lItem).Tag = LV.ListItems(lItem).Text

Else

LV.ListItems(lItem).Tag = LV.ListItems(lItem).Tag & ";" & _
LV.ListItems(lItem).SubItems(lSubitem)

End If
Next lSubitem

Next lItem

LV.Tag = "Loaded " & lItem
Debug.Print LV.Tag & " Items"

InitErr:

Select Case Err.Number
Case 0:

Case 91:
Case Else:
Debug.Print Err.Number; Err.Description

End Select

End Sub

Private Sub lvButtons_H4_Click()
Dim response As Integer
response = MsgBox("?", vbYesNo + vbInformation, "")
If response = vbYes Then

End
End If

End Sub

Private Sub lvButtons_H5_Click()
frmMain.Show 1

End Sub

Private Sub lvButtons_H6_Click()
Text1.Text = ""
End Sub

Private Sub lvButtons_H7_Click()
frmMain4.Show 1

End Sub

Private Sub Text1_Change()

ListView.ListItems.Clear

Call dbConnect
sql = "SELECT * FROM tbl_info WHERE info_name LIKE '" & Trim(Text1.Text) & "%'"
Set rs = New ADODB.Recordset

rs.Open sql, conn, adOpenDynamic, adLockOptimistic

If Not rs.EOF Then
Do Until rs.EOF

Set Item = Me.ListView.ListItems.Add(, , rs!id_info, , "Custs")
With ListView

Item.SubItems(1) = rs!info_name
Item.SubItems(2) = rs!info_address
Item.SubItems(3) = rs!phone
Item.SubItems(4) = rs!mobile
Item.SubItems(5) = rs!mdate
Item.SubItems(6) = rs!mone
Item.SubItems(7) = rs!tech
Item.SubItems(8) = rs!modle
Item.SubItems(9) = rs!os
Item.SubItems(10) = rs!ok

End With

rs.MoveNext

cmdDelete.Enabled = True

cmdEdit.Enabled = True
cmdAdd.Enabled = True
lvButtons_H4.Enabled = True
lvButtons_H3.Enabled = True
abc.Enabled = True

lvButtons_H2.Enabled = True
lvButtons_H5.Enabled = True
cmdRefresh.Enabled = True

Loop

End If

rs.Close: Set rs = Nothing

End Sub

Sub Form_QueryUnload(cancel As Integer, UnloadMode As Integer)
Dim reply As Integer
reply = MsgBox("?", vbInformation + vbYesNo, "")
If reply = vbNo Then
cancel = 1
End If
End Sub
Private Sub Timer3_Timer()
Label2.Caption = Me.ListView.ListItems.Count
End Sub
Private Sub Timer4_Timer()
Form11.Caption = " "
End Sub
Private Sub listview_Mouseup(Button As Integer, Shift As Integer, x As Single, y As Single)
If Button = 2 Then '
Me.PopupMenu mnuRightClick 'Show the popup menu
End If
End Sub
Private Sub mnuDelete_Click()
End Sub
Private Sub lvwPeople_KeyUp(KeyCode As Integer, Shift As Integer)
End Sub
Private Sub refresh_click()
Call loadRecords
End Sub
Private Sub excel_click()
Form125.Show 1
End Sub
Private Sub info_Click()
Form4414.Show 1
End Sub
Private Sub details_Click()
If Me.ListView.ListItems.Count = 0 Then
MsgBox "", vbInformation, ""
Exit Sub
End If
Form3.Show 1
End Sub

Private Sub exit_Click()
Unload Me
End Sub.
-------------------------------
this form is named form 11 so far so good.
now i made another form that contains 3 text boxes and i added a combobox
by the way the name of the database in form 11 that holds the list is called "database"
how do i connect to form 11 and displaying the user name in the combobox in the new form that i just created?
like i said im new in vb 6 and i need a slow explanation .
thanks for the help

help plsss..

i had a problem using list view control...
i made a program using the said control....
but when i load the program the column headers didn't appear on the screen...
what should i do???...

Combobox

can i have your email if i have any questions to ask you about vb 6?

E-mail

Yes of course. Here it is: chrzgt7@hotmail.com

change text

what did you meen by Change the Index property of each text box to: 2, 3, 4, 5 and6 ?

combobox

the code worked perfect but i have en error
wrong number of arguments some thing like that

this error means, the object

this error means, the object which you are trying to use hasnt been set .. like
you use the statement

set Obj = listView.Addtime (...)

if this Obj hasnt been set and you try to use it you will get this "Object not set" error. The objects which are not set are actually nothing, and when you try to use them, you are trying to use nothing.

i have a question if you can help me

i added to this database people that have to give me money and didnt pay yet..how do i caulculate the amount of the total money that the people needs to give me according to the database..
for example: joey needs to give me 500 dollars and didnt pay and greg didnt pay 300 .
how can i show in a label the amount total of money that they didnt pay yet.
please help me im kind of new in here
thank you

Sum the money

You have to use the SUM() in a SQL statement.

Let's say that the money you enter every time is stored in the table field named MoneyOwned. As you can understand, the label should display the sum of the MoneyOwned field. Here is what you have to do:

mobjCmd.CommandText = "SELECT SUM(MoneyOwned) as PayMe FROM table_name"
SET mobjRst = mobjCmd.Execute

And finally: Label1.Caption = Format(mobjRst!PayMe, "$ #,##0.00")

I believe this should work! Looking forward the results...

vb 6

ChrisGT7 u are a pro
thanks for the help!!!!!!!!!!!

Arik

thank you worked :)

im using listview by the way

im using listview by the way

error

soy what do i need to do to bot get this error?

Please Help

the balance of tbStok can't update, please fix my code.....

Private Sub cmdDel_Click()
Dim a, kb, sat As String
Dim qty, Balance As Double

a = txtNo_Inv.Text
Set rsA = New ADODB.Recordset
rsA.Open "SELECT * From tbSalesDetail WHERE No_Inv ='" & a & "'", cn, adOpenDynamic, adLockOptimistic

If rsA.RecordCount > 0 Then
If MsgBox("Delete?", vbQuestion + vbYesNo, "Confirmation") = vbNo Then
Exit Sub
Else
''''''''''''''''''''XXXXXXXXXXXX""""""""
Set rsB = New ADODB.Recordset
rsB.Open "SELECT * From tbSalesDetail WHERE No_Inv = '" & a & "'", cn, adOpenDynamic, adLockOptimistic

If Not rsB.EOF Then
rsB.MoveFirst
Do While Not rsB.EOF
kb = rsB.Fields(1).Value
qty = rsB.Fields(2).Value
sat = rsB.Fields(3).Value

Set rsC = New ADODB.Recordset
rsC.Open "SELECT * from tbStock WHERE Item_Code = '" & kb & "'", cn, adOpenDynamic, adLockOptimistic
If rsC.EOF Then
Set rsD = New ADODB.Recordset
rsD.Open "SELECT * From tbStock", cn, adOpenDynamic, adLockOptimistic
rsD.AddNew
rsD.Fields(0).Value = kb
rsD.Fields(1).Value = qty
rsD.Fields(2).Value = sat
rsD.Update
rsD.Requery
Else
Set rsE = New ADODB.Recordset
rsE.Open "SELECT * from tbStock WHERE Item_Code = '" & kb & "'", cn, adOpenDynamic, adLockOptimistic
rsE.Clone
Balance = rsE.Fields(1).Value
Balance = Val(Format(Balance + qty))
End If

If Not rsB.EOF Then
rsB.MoveNext
End If
Loop
End If
'''''''''ZZZZZZZZZZ'''''''''''
Set rsG = New ADODB.Recordset
rsG.Open "SELECT * From tbSales WHERE No_Inv = '" & a & "'", cn, adOpenDynamic, adLockOptimistic

If Not rsG.EOF Then
Set rsF = New ADODB.Recordset
rsF.Open "SELECT tbSalesDetail.*, tbSalesDetail.No_Inv FROM tbSalesDetail WHERE (tbSalesDetail.No_Inv = '" & a & "')", cn, adOpenDynamic, adLockOptimistic
If Not rsF.EOF Then
Do Until rsF.EOF
rsF.Delete
rsF.MoveNext
Loop
End If
rsG.Delete
End If
End If
End If

ListView1.ListItems.Clear
Form_Load
txtNo_Inv.Enabled = True
txtNo_Inv.SetFocus

End Sub

visual basic (listview)

please please i need your help! am a student in college and am doing a project on HRM system. Now i want to produce a system which will allow users to select/choose specific records from access database and then displayed on listview.

list view

..i want help.. I had used a list view control in the enrollment system we were asked to do as a completion for modeling and simulation subject. but i have no idea on how could i move the records shown in the list view to my data report....i have not yet tried that but i doubt i can't do this on my own...so thanks i found this site..maybe you can help me...I expect an answer to my problem...please help me...our defense is set on Oct. 29,'10....please... i really need your help.....anyway...the examples above is a big help....it's too long....but i can use it...thank you....

VB6 inventory

Could anyone help me for my inventory system ?

I'm trying to subtract some value in my table using data environment with a particular
ID number . it only works in the first record .

could anyone help me for my case study project ?

thanks in advance

auto select using mouse scroll with 3 listview control

Please urgent

I have 3 listview control
LV a = table customer
LV b = table work order confirmation (woc)
LV c = table product

How to selected row When LV a i am move scroll up or down using mouse then LV b automatic view work order by id customer and LV c automatic show product by no woc...?

Thanks

Please help me

please help me for a simple code to connect a database to a listview.. im only a begginer, please give me a simple code. using module... bec im making a project about inventory system.. please please help me.. just e mail me at motonoaji69@gmail.com.

tnx a LOT! hope u will help me..

Hard

this is a mess for begineers programmer who want to start with using ADODB in vb6.

db list control

cfdfsir,
i want the coding of databound list control 6.0. plz help me

ListView

I have a problem in ListView and also in ListBox control, "I couldn't add more than 100 items" so what shoud i do?

Please Help me!!!! What

Please Help me!!!!

What control in visualbasic6 should i use when i want to capture a picture?? and How??

Find no part in the program

Süper bir uygulama jack sana katılıyorum Birde arama kısmı olsaydı programda çok daha güzel olabilirdi.

Jack sana yardım etmek isterdim ama listview de basit bir arama kodu bende mevcut istersen yazabilirim

So... Command Find Button?

Very nice application, but only one found, the search button is missing if someone can help me if I remain grateful to those here who will write code to friends, thank you ...
In the meantime get from the database search code or search code, or get in listview I need urgent matter

About Coding

Sir
We need the following buttons coding with handler of debug.

New, Next, Privious, Last, First, Delete, Search, Find, Combo box with reports, List box with combo, Calander Date with form, Calender Date with reports etc

Thanks.

Sher_bci@yahoo.com

Listview

Hi how to listview search / find ???
Please help me

List View

Hi,
is it possible to type directly into the list view and save? i have a listview that i have customezed with column headers and codes to include grid lines now i just wanna be able to type text and save to an access data base, the followin is my code for grid lines

Private Sub chkGridLines_Click()

Dim rStyle As Long
Dim r As Long

'get the current ListView style
rStyle = SendMessageLong(txtSiteHist.hwnd, LVM_GETEXTENDEDLISTVIEWSTYLE, 0&, 0&)

If chkSelectMode.Value = 0 Then
'remove the extended bit
rStyle = rStyle Xor LVS_EX_GRIDLINES

ElseIf chkSelectMode.Value = 1 Then
'set the extended bit
rStyle = rStyle Or LVS_EX_GRIDLINES

End If

'set the new ListView style
r = SendMessageLong(txtSiteHist.hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, 0&, rStyle)

End Sub

i would have loved to post a screen shot of the list view with grid lines, anyways please assist me with this problem or if there is another alternative control that can help me achieve the same results, Thanks,
Regards

Listview

Where can I find that listviewcontrol? I can't find it...pls suggest me..

thanks...

Add "Microsoft Windows

Add "Microsoft Windows Common Control 6.0" from componnents in VB 6.0

Great Help

I'm studying vb6 for a while and I find it difficult to understand how to use the ListView control. This Tutorial thought me how in a couple of hours.

To further my study, I created my own program using ListView. It was a success... but... with one funny difference. The selected record loses its highlight when I press any action buttons. I scanned my codes for possible errors, even compared it line by line with the tutorial... Until, I check each object properties. Fortunately, the first object I checked is the ListView control itself, its my newest control anyway. The problem lies in the ListView Property:

HideSelection (default is True)

with the following description:

Determines whether the selected item will display as selected "when the ListView loses focus".

Which is exactly was what happening as I navigate my training project. I'm actually happy to see this property, now my training project is almost as good as the tutorial. I hope, when I create a real application, I can surpass the tutorial though.

Thanks, its a great help and exercise.

Good coding

Good coding

Thank you very much.

Thank you very much.

Thank you

Thank you very much that was very helpfully

best regards
Walid

want to write query of mssql from vb6 by using ado connection

hello,
please help me in writing query from visual basic 6 in mssql2000 in ado connection

Really great sample. Simple

Really great sample. Simple and to the pont.
thanks.

listview

Where can you find that listviewcontrol? I can't find it. What is the name of the dll, ocx so I can add it to my components

thanks!

Wanna ask...

Nice code..it really did help me a lot.. thanks

by the way

what does this code mean "If Not ValidateFormFields Then Exit Sub"???
i was just curious... can anyone explain it to me???

Hi, I think the line "If Not

Hi,
I think the line "If Not ValidateFormFields Then Exit Sub" means if the validation of the data is not successful program will not proceed with the Save operation. The function should contain whatever the validation is necessary for each inputted data.

To the author of the program,
Thanks a lot, this has helped me so much....

cool

thanks i was searching for the same thing....got it

thanks

i had know about listview control
but you told me how to implement it...

the information provided by you is fantastic and very useful

i m show much thankful to u

Too long!

Too long!

IWHNE I RUN THE PROJECT . IT

IWHNE I RUN THE PROJECT . IT SHOW THE ERROR MESSAGE "Private Sub PopulateListItem(pobjListItem As ListItem)" Can't find the project or lib.
"""

mblnUpdateInProgress

what is the function of mblnUpdateInProgress in this code?

The purpose of

The purpose of mblnUpdateInProgress, to me, is so that if the user attempts to close the application while UpdateInProgress is flagged TRUE, the msgbox will fire telling the user to finish their current action before closing the window.

Using with VBA

Hi.

I´ve a question about this great VB example.
Is there a possibility to use in VBA?

I tried to customize but I wasn't succesful.
Could anybody help me please?

Greets Phoenix

No it cannot.

No it cannot.

lvw with vba cannot ? Yes it can

Hello, I'm currently using it in a MsAccess vba project

To use it :
in your MsAccess project, call the vba dev interface (ALT + F11 key)
Tools > References > search for: c:\windows\system32\mscomct2.ocx

it will add Microsoft Common Controls-2 6.0 (SP4) to your project and then you will be able to drag/drop the Listview control into your form
give it a name (lvwMain for instance)
And then in your project you simply declare and set the listview object;
note : in fact in MsAccess you don't have to declare the object if you code into your form, it is recognized by its name already ( me.LvwMain....)

Dim Lvw1 as MSComctlLib.ListView
set Lvw1 = me.lvwMain.Object

Dim lvWidth As Integer
lvWidth = Me.lvwMain.Width

'Set listview object presentation
With lvw1
.View = lvwReport
.GridLines = True
.FullRowSelect = True
.LabelEdit = lvwManual
.ListItems.Clear
End With

'add column headers
With lvw1
.ColumnHeaders.Clear
.ColumnHeaders.Add , , "{@COID}", lvWidth * 0.10, lvwColumnLeft
.ColumnHeaders.Add , , "{@COL1}", lvWidth * 0.15, lvwColumnCenter
.ColumnHeaders.Add , , "{@COL2}", lvWidth * 0.12, lvwColumnCenter
End With

..etc....
and there you go;

hope this will help;

and anyway, the sample is useful, quite complete and clear, thanks again

Dan.

cmdSave

what is mstrMaintMode?

wow

thanks for this! this can help me complete my project at school. its been 2 years and i havent done it yet. its keeping me from graduating! anyways, thanks a lot. i love vb6 and i hope i learn vb.net soon. thanks really! cheers here from the Philippines.

goog yar thanks very much

hey good job yar

great thnx ..ossam keep it up

thnks a lot

nice.....

simple codes ... easy to understand..

thanks.. this would help a LOT.

Excellent work, Yet very simple and nice coding...

Hi, Dude
Being an expert in VB for a decade i use controls when i really need it.
for a quick search and easy to understand code, i recomend all new to vb and experts like me to check the code above.
for RAD development.
Thanks again,
God Bless.

vb application

i wonder why the site has provided all the codes for vb applicattion but with the exception of "search command"
cant u put the search command just as uve put the other commands?

Datagrid Control

Hello VBProgrammer,

Your program is very WOW! for me as a beginner programmer in VB. Can you help me do the same program but using the Datagrid Control instead of the listview? please email me :( Your help is very much appreciated..Thank you very much..More Power!! :))

Pl.help me for master/detail form using adodc and data grid

I am just beginer in vb6. I want to design a form for Invoicing/Billing.
In a master detail form, adodc and datagrid control is required .
If anyone send me source code of the program. I really will be grateful.
Thanks
Balaram Dey

Simple and Very Useful product

Dear Guruji,

excellent work.
Congatulattions!

Regards,
udaya K.

Best Sample for me

Best regards

Thank you

thank you for providing such a perfect help..
thanx a lot :)

listview icons

thank you
nice and simple code
pls send me simple code to add an icon to list view
regards

how about...

this useful for a beginner like me. how about you add an option for a "SEARCH". the rest is perfect. hope you could email the revise/addtional code

email:molfato@yahoo.com

its really good but beginars

its really good but beginars using access database cannot use this

Listview display problem

Just what i was looking for. 1 small problem i got, is that listview displays rubbish characters (greek language is used on the table of the mdb), probably problem with utf-8. Any solution suggested?

IS THIS CODE APPLICABLE IN MSSQL SERVER 2005?

is there anyone has a code sample shown above using MSSQL SERVER 2005? email me pls.... i nid help.... wendeered@gmail.com.... tnx 2 som1 hu wil help me.... i wil wait 4 ur help....

I'm trying to add 3 more

I'm trying to add 3 more fields to be updated into the database but when i add the code for the fields its almost like they dont exist.

keeps telling me either my update SQL statement is wrong or my insert into is wrong depending if i choose add or update

the 3 fields im trying to add are year make and model

please email if you can help
jcobb5728@charter.net

HELLO FOR THE FIRST TIME

PLEASE I NEED TO UNDERSTAND SOMETHING..
if you are using sql server and you make a connection with a server using a connections tring,you must also use the microsoft jet 4 oledb connection for handling the records????

very good

very good

using ADO

TNX it really helps me

how to add a find button???

very informative. i just want to ask on how to add a find button?

TreeView and Show data to Text box/ Grid.

Please help me. How to using Ado connection TreeView and Show data to Text box/ Grid.

how to edit ado in vb6 runtime

can you have a simple code not in the list below because its to hard to understand. my approach in vb6 is different in the code. i was so thankful if you have those simplest code

Can i have a complete code of Customer Table Maintenance

Hi, can u give a complete code of this example..
please send it thru my emai address..

Your favor is very much appreciated

Thank you...

Very informative site.... especially learning the ADO but it is very well explained that a reader will surely understand the basic of it... Through it i able to expand my confusions on connecting a database... This make a foundations for every programmer to be... and a reference for those intermediate and even expert...

I salute you TheVBProgrammer for doing a great jobs... making a complicated things easier...

Keep up the good works...

where can i download this

where can i download this program

vb6

I HAVE SEEN BUTTONS WITH ICON, HOW DO I DO THAT

see above the line where it

see above the line where it is written "Hw did u like this article"
there you will find a link download the application here...

click on link

Well Done...Yipeeeeeeee...!!!!

Thanx a lot Dear

A nice coding

Thankyou so much

Thanks very much! It's

Thanks very much! It's interesting!

Visual Basic 6.0 Tutorials

I enjoyed your tutorial on using ADO and the listing control but since i am still a beginner i would like you to send me the breakdown of vb6.0 tutorial so that i could learn, grow and become a great programmer like you. I would be gratefull if my request is granted.
Just keep up with the good work and God Bless
Thanks

Great!!!

This is good stuff, learned a lot just browsing the code!

more

how about the checkbox option? a minimal lecture will be greatly appriciated. thanx
selecting the listview and getting its value on the second 3rd or forth row, will be good to those who want to enhance their skills.

excellent

thanks for the help

Using ADO and the ListView control

thank you very much...the information presented here helped me a lot.
thank you

Ado sample

Thank's A lot.

Good

Malo aupito.
Oku faka'ofo'ofa
Thank you very much

Using Ado connection TreeView and Show data

Dear Vb Coder,
Congratulation.
Using Ado and ListView Control code is fine. Please help me. How to using Ado connection TreeView and Show data to Text box/ Grid.