Hi! Can someone tell me on how could I display the data from my SQL to a ListView? I only have one column to display. Thank you very much and God Bless! :)

here is a sample program for what u want to do.. i have used the NorthWind Database. u can use yours.


Complete Coding:

Imports System.Data.SqlClient
Public Class Form1
    Dim conn As SqlConnection
    Dim cmd As SqlCommand
    Dim da As SqlDataAdapter
    Dim ds As DataSet
    Dim itemcoll(100) As String

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.ListView1.View = View.Details
        Me.ListView1.GridLines = True

        conn = New SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=id;Password=pass")

        Dim strQ As String = String.Empty

        strQ = "SELECT * FROM Northwind.dbo.Products"

        cmd = New SqlCommand(strQ, conn)
        da = New SqlDataAdapter(cmd)
        ds = New DataSet
        da.Fill(ds, "Table")

        Dim i As Integer = 0
        Dim j As Integer = 0

        ' adding the columns in ListView
        For i = 0 To ds.Tables(0).Columns.Count - 1
            Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
        Next

        'Now adding the Items in Listview
        For i = 0 To ds.Tables(0).Rows.Count - 1

            For j = 0 To ds.Tables(0).Columns.Count - 1

                itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
            Next

            Dim lvi As New ListViewItem(itemcoll)
            Me.ListView1.Items.Add(lvi)

        Next
    End Sub
End Class
Attachments Untitled.png 26.76 KB

Thanks! I did it with this:

mycurrentconnection.Open()

        Dim qstn As String
        ListView1.Columns.Clear()
        Dim cmd As New OleDbCommand("select Question from Questions", mycurrentconnection)
        cmd.CommandType = CommandType.Text


        Dim reader As OleDbDataReader = cmd.ExecuteReader()

        While reader.Read()
            qstn = reader("Question").ToString
            ListView1.Items.Add(qstn)

        End While
        reader.Close()


        mycurrentconnection.Close()

my only problem is, my column name doesn't show. :)

Me.ListView1.Columns.Add("Question")

add above line before the while loop. it will add a column name Question

Edited 5 Years Ago by sandeepparekh9: n/a

listView1.View = View.list - this works but displays no column name.
listView1.View = View.Details - I think this is appropriate but it does not work on mine. :(

I would like my listview to be like yours. However, if I set my listview view to details, it shows nothing.

if u are only having one column then..add a column manually from Design View in Visual Studio.

here a is a snap of how to do it

just change to name property to what ever name u like..

Attachments Untitled.png 32.08 KB
This question has already been answered. Start a new discussion instead.