Friday, March 21, 2014

VB.Net fill SqldataReader to listview

Private Sub FillListViewQueryData(ByRef sqlData As SqlDataReader)
        Dim lvTemp As ListViewItem = New ListViewItem()
        'Dim dSet As New DataSet
        'Dim dr As DataRow
        Dim lvwColumn As ColumnHeader
        Dim itmListItem As ListViewItem
        Dim shtCntr As Short
        Dim shtLC As Short

        Me.Cursor = Cursors.WaitCursor

        'Remove any existing contents from our listview.
        lv.Clear()

        Try

            For shtCntr = 0 To sqlData.FieldCount() - 1
                lvwColumn = New ColumnHeader()
                lvwColumn.Text = sqlData.GetName(shtCntr)
                lv.Columns.Add(lvwColumn)
            Next

            shtLC = 1       'Initialize loop counter.
            Do While sqlData.Read
                itmListItem = New ListViewItem()
                itmListItem.Text = sqlData(0)

                For shtCntr = 1 To sqlData.FieldCount() - 1
                    If sqlData.IsDBNull(shtCntr) Then
                        itmListItem.SubItems.Add("")
                    Else
                        itmListItem.SubItems.Add(sqlData.GetValue(shtCntr).ToString)
                    End If

                Next shtCntr

                lv.Items.Add(itmListItem)

            Loop

            'lblRecdCtr.Text = "Records: " & lv.Items.Count

            'Resize each column to the size of the text in the column header.
            For Each lvwColumn In lv.Columns
                lvwColumn.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)
            Next

            sub_ShadeRows()

        Catch ex As Exception
            MessageBox.Show(ex.Message, vbNullString, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            lvwColumn = Nothing
            lvTemp = Nothing
        End Try

        lblRecordCount.Text = "Record count: " & lv.Items.Count

        Me.Cursor = Cursors.Default

    End Sub

 Private Sub sub_ShadeRows()
        Dim itm As ListViewItem
        Dim iLC As Integer = 0

        For Each itm In lv.Items
            'Shade every other row for easier readability
            If (iLC Mod 2) Then
                itm.BackColor = Color.Silver
            Else
                itm.BackColor = Color.White
            End If
            iLC += 1
        Next itm

        lv.Refresh()
    End Sub

No comments:

Post a Comment