Hi All,
Below is an example to load the listview, and i believe it may help to reduce the coding on it.
Step 1: Create a form, named it "Form1" and add a listview, named it "Listview1"
step 2: Configure the listview's look by choosing "Details".
step 3: Add the Some "columns' and a button, named it as "Button1". In this case, I add 4 columns which is to show the customer details
step 4: Add a class, named it as "LoadListView.vb".
step 5: Add the code to the LoadListview Class.
Imports System.Data.SqlClientPublic Class LoadListview Public Sub loadlistview(ByVal cs As String, ByVal ColumnNum As Integer, _ ByVal listviewName As ListView, ByVal ssql As String, _ ByVal ColumnName() As String) Dim columnData(8) As String Dim lvi As ListViewItem Dim command As New SqlCommand Dim dr As SqlDataReader Dim Conn As SqlConnection = New SqlConnection Dim count As Integer Dim i As Integer listviewName.BeginUpdate() 'conn.Open() Try Conn.ConnectionString = cs Conn.Open() command = New SqlCommand(ssql, Conn) dr = command.ExecuteReader listviewName.Items.Clear() 'Clear the listview before adding While dr.Read() For i = 0 To ColumnNum columnData(i) = dr.GetValue(dr.GetOrdinal(ColumnName(i))).ToString Next lvi = New ListViewItem(columnData) listviewName.Items.Add(lvi) count = count + 1 End While listviewName.EndUpdate() 'End of updating Catch ex As Exception MsgBox(ex.Message) Finally If Conn.State = ConnectionState.Open Then Conn.Close() 'Close the database connection if it is still open End Try End SubEnd Class====================================================
Explaination:
CS = Connection String for databaseColumnNum = No of column(count from 0, if I had 4 columns so i will only write 3)ListviewName = Name of your listview(In my case is "ListView1")ssql = SQL statementColumnName() = Array of the database column name, which are going to show at the list viewStep 6: Add the Code to "Form1.VB"
Public Class Form1 Private connString As String = "Data Source=IBM-PC\SQLEXPRESS;Initial Catalog=CustomerSystem;Persist Security Info=True;User ID=CUST;Password=CUST" Private LLV As New LoadListview Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sql As String = "select * from custmaster" Dim colname() As String = {"company", "custcode", "telephone", "address"} LLV.loadlistview(connString, 3, ListView1, sql, colname) End SubEnd ClassStep 7: Click the Button1 to see the result
========================================================================
End of the Example
From the given code, you can try to change to suit your purpose.
Please leave comment, if you like it.