How can I populate a listview from another form passing the SQL statement from this form to the other form with the listview showing the result of the query?

You can create a sub procedure in the destination form that will take the SQL statment as a string. Then fill the ListView from that sub procedure.

For example:

    'In DestinationForm 
    Protected Friend Sub FillListView(ByVal sSQL As String)
        Dim da As New OleDbDataAdapter(sSQL, New OleDbConnection("YourStringHere"))
        Dim ds As New DataSet
        Try
            da.Fill(ds, "MyTable")
            If Not IsNothing(ds.Tables("MyTable")) Then
                If ds.Tables("MyTable").Rows.Count > 0 Then
                    For Each dr As DataRow In ds.Tables("MyTable").Rows
                        Dim lvi As New ListViewItem

                        lvi.Text = dr("MyCol1")
                        lvi.SubItems.Add(dr("MyCol2"))
                        lvi.SubItems.Add(dr("MyCol3"))

                        MyListView.Items.Add(lvi)
                    Next
                Else
                    MsgBox("No rows were returned by the query!", _
                    MsgBoxStyle.Information, "Oops!")
                End If
            Else
                MsgBox("No objects were returned from the database.", _
                MsgBoxStyle.Information, "Oops!")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error!")
        Finally
            da.Dispose()
            ds.Dispose()
        End Try
    End Sub

To fill the ListView, call the procedure like so:

frmMyFormInstance.FillListView("YourQueryHere")

@Begginnerdev, Your codes are quite right. But it can perform an exception due to Closed DataConnection. Nowhere you open the Connection Object.

My apologies, I typed the previous code straight into the code window.

Don't mind, about the pointing to your codes unwilling mistake. It should be

Dim da As New OleDbDataAdapter(sSQL, New OleDbConnection("YourStringHere").Open)

Or also eit could be

Dim Conn as New OleDb.OledbConnection

Conn.ConnectionString="Your Connection String"

If Conn.State=OleDbconnection.Opened Then conn.Close()

Conn.Open()

Dim da As New OleDbDataAdapter(sSQL, Conn)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.