0

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?

3
Contributors
4
Replies
47
Views
3 Years
Discussion Span
Last Post by Shark_1
0

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")

Edited by Begginnerdev

0

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

0

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)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.