The .NET Developer Community

Populating Data into a ListView using a DataReader in VB.NET

rated by 0 users
This post has 0 Replies | 0 Followers

krvikramraju
Top 500 Contributor
Bangalore, India
Since 3/19/2003
Posts 401
Reputation 2,245
Vikram Raju (krvikramraju) Posted: 3/26/2003 8:08 PM
NOTE: lvoorders -> is the ListView and its View property is set to Detail, GridLines property = TRUE and I am using the default NORTHWIND Database

Code:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Dim strsql As String
    Dim reader As System.Data.SqlClient.SqlDataReader
    
    strsql = "Select customerid,orderid,employeeid From Orders"
    
    SqlCommand1.CommandText = strsql
    SqlConnection1.Open()
    
    reader = SqlCommand1.ExecuteReader
    
    'This sets the columns of the ListView to the same column names of the table in the database
    With lvoorders
        .Columns.Add(reader.GetName(0), 80, HorizontalAlignment.Center)
        .Columns.Add(reader.GetName(1), 80, HorizontalAlignment.Center)
        .Columns.Add(reader.GetName(2), 80, HorizontalAlignment.Center)
    End With

    'Now scrolling through the DataReader and populating the ListView with the data
    While reader.Read
        Dim ls As New ListViewItem(reader.Item("customerid").ToString()) ' you can also use reader.GetSqlValue(0)
        ls.SubItems.Add(reader.Item("orderID").ToString())
        ls.SubItems.Add(reader.Item("employeeid").ToString())
        lvoorders.Items.Add(ls)
    End While

    SqlConnection1.Close()

End Sub

Next code is for trapping the keypress event and search for the keychar present in the data and then ensure it is the visible row in the ListView

Code:
Private Sub lvoorders_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles lvoorders.KeyPress
    Dim i As Integer
    For i = 0 To lvoorders.Items.Count - 1
        If lvoorders.Items(i).Text.Substring(0, 1) = Char.ToUpper(e.KeyChar) Then
            lvoorders.Items(i).Selected = True
            lvoorders.Items(i).EnsureVisible()
        End If
    Next
End Sub

--Vikram Raju
"Education is the manifestation of the perfection already in man"

Page 1 of 1 (1 items) | RSS
Copyright 1998-2017 vbCity.com LLC