I'm stuck, can someone teach me on how to populate my listview using database.

Recommended Answers

All 3 Replies

hi

Put a list view to form

use following code:

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

        Dim conn As New SqlConnection("Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=id;Password=pass")

        Dim strQ As String = String.Empty

        strQ = "SELECT * FROM yourtablename"

        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)
            Me.ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)

        Next
    End Sub

Thank you sir.

how to use that itemcoil??

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.