Solved

Example needed for using Sortedlist

Posted on 2004-08-23
5
2,164 Views
Last Modified: 2012-06-27
Hi,

The couple of books I read on VB.NET have omitted to explain what Sortedlists are and how to use them. I would be grateful for an explanation and a small clear example.
 
0
Comment
Question by:tariqanis
  • 3
5 Comments
 
LVL 27

Expert Comment

by:planocz
ID: 11873703
Heres is a sample for Listviews....

'FORM

   Private Sub Listview_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles Listview.ColumnClick
        ' Determine whether the column is the same as the last column clicked.
        If e.Column <> sortColumn Then
            ' Set the sort column to the new column.
            sortColumn = e.Column
            ' Set the sort order to ascending by default.
            lvwCustomers.Sorting = SortOrder.Ascending
        Else
            ' Determine what the last sort order was and change it.
            If lvwCustomers.Sorting = SortOrder.Ascending Then
                lvwCustomers.Sorting = SortOrder.Descending
            Else
                lvwCustomers.Sorting = SortOrder.Ascending
            End If
        End If
        ' Call the sort method to manually sort.
        lvwCustomers.Sort()
        ' Set the ListViewItemSorter property to a new ListViewItemComparer object.
        lvwCustomers.ListViewItemSorter = New ListViewItemComparer(e.Column, lvwCustomers.Sorting)
    End Sub

'CLASS

' Implements the manual sorting of items by columns.

Class ListViewItemComparer
    Implements IComparer
    Private col As Integer
    Private order As SortOrder

    Public Sub New()
        col = 0
        order = SortOrder.Ascending
    End Sub
    Public Sub New(ByVal column As Integer, ByVal order As SortOrder)
        col = column
        Me.order = order
    End Sub
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
                        Implements System.Collections.IComparer.Compare
        Dim returnVal As Integer = -1
        returnVal = [String].Compare(CType(x, ListViewItem).SubItems(col).Text, _
                        CType(y, ListViewItem).SubItems(col).Text)
        ' Determine whether the sort order is descending.
        If order = SortOrder.Descending Then
            ' Invert the value returned by String.Compare.
            returnVal *= -1
        End If
        Return returnVal
    End Function
End Class

0
 
LVL 27

Expert Comment

by:planocz
ID: 11873712
forgot to change....
 lvwCustomers to Listview
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 11874675
A SortedList stores entries as a Key/Value pair like a HashTable, but sorts the entries based upon the Key value.  (A HashTable stores Key/Value pair entries in the order they were inserted.)

Each entry placed into a SortedList must have a unique Key value.  Instead of retrieving values by Index as in an Array, you usually retrieve values by Key.  The value associated with a Key is an object, which means it can be another simple data type like a string, or a complex data type like an intance of a class.

Idle_Mind
0
 

Author Comment

by:tariqanis
ID: 11877422
Hi planocz, Idle_Mind

Thanks for both of you, but I need one of you to start out by showing me how to first create a sortedlist, fill it with data, and retrieve the data from it....



Idle_Mind started out with a good explanation, and I had hoped for some kind of illustration while planocz is showing an exmaple of how to use it without explaining first how to creat it and set out the goal for creating it.

Maybe I neglected to say I am a newbie at this, but I am.
0
 
LVL 27

Accepted Solution

by:
planocz earned 200 total points
ID: 11880336
Here is a sample of viewing a customer name and ID number from a database.

'FORM

Imports System
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports CrystalDecisions.CrystalReports.Engine
Public Class frmView
    Inherits System.Windows.Forms.Form
    Dim sTableName As String
    Dim bAlpha As Boolean

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        InitializeListview()
    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        Catch Exp As NullReferenceException
            '    Bypass this error
        Catch Exp As Exception
            MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents lvwReports As System.Windows.Forms.ListView
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents btnAF As System.Windows.Forms.Button
    Friend WithEvents btnGL As System.Windows.Forms.Button
    Friend WithEvents btnMR As System.Windows.Forms.Button
    Friend WithEvents btnSZ As System.Windows.Forms.Button
    Friend WithEvents lblView As System.Windows.Forms.Label
    Friend WithEvents lblView1 As System.Windows.Forms.Label
    Friend WithEvents btn09 As System.Windows.Forms.Button
    Friend WithEvents btnOK As System.Windows.Forms.Button
    Friend WithEvents btnCancel As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmView))
        Me.lvwReports = New System.Windows.Forms.ListView
        Me.GroupBox1 = New System.Windows.Forms.GroupBox
        Me.btnCancel = New System.Windows.Forms.Button
        Me.btnOK = New System.Windows.Forms.Button
        Me.btn09 = New System.Windows.Forms.Button
        Me.btnSZ = New System.Windows.Forms.Button
        Me.btnMR = New System.Windows.Forms.Button
        Me.btnGL = New System.Windows.Forms.Button
        Me.btnAF = New System.Windows.Forms.Button
        Me.lblView = New System.Windows.Forms.Label
        Me.lblView1 = New System.Windows.Forms.Label
        Me.GroupBox1.SuspendLayout()
        Me.SuspendLayout()
        '
        'lvwReports
        '
        Me.lvwReports.AllowColumnReorder = True
        Me.lvwReports.FullRowSelect = True
        Me.lvwReports.Location = New System.Drawing.Point(16, 16)
        Me.lvwReports.MultiSelect = False
        Me.lvwReports.Name = "lvwReports"
        Me.lvwReports.Size = New System.Drawing.Size(340, 216)
        Me.lvwReports.TabIndex = 0
        '
        'GroupBox1
        '
        Me.GroupBox1.Controls.Add(Me.btnCancel)
        Me.GroupBox1.Controls.Add(Me.btnOK)
        Me.GroupBox1.Controls.Add(Me.btn09)
        Me.GroupBox1.Controls.Add(Me.btnSZ)
        Me.GroupBox1.Controls.Add(Me.btnMR)
        Me.GroupBox1.Controls.Add(Me.btnGL)
        Me.GroupBox1.Controls.Add(Me.btnAF)
        Me.GroupBox1.Location = New System.Drawing.Point(384, 12)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(144, 252)
        Me.GroupBox1.TabIndex = 2
        Me.GroupBox1.TabStop = False
        Me.GroupBox1.Text = "Smaller Groups"
        '
        'btnCancel
        '
        Me.btnCancel.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnCancel.Location = New System.Drawing.Point(28, 212)
        Me.btnCancel.Name = "btnCancel"
        Me.btnCancel.Size = New System.Drawing.Size(88, 24)
        Me.btnCancel.TabIndex = 8
        Me.btnCancel.Text = "&Cancel"
        '
        'btnOK
        '
        Me.btnOK.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnOK.Location = New System.Drawing.Point(28, 180)
        Me.btnOK.Name = "btnOK"
        Me.btnOK.Size = New System.Drawing.Size(88, 24)
        Me.btnOK.TabIndex = 7
        Me.btnOK.Text = "&Ok"
        '
        'btn09
        '
        Me.btn09.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn09.Location = New System.Drawing.Point(28, 148)
        Me.btn09.Name = "btn09"
        Me.btn09.Size = New System.Drawing.Size(88, 24)
        Me.btn09.TabIndex = 6
        Me.btn09.Text = "0 to 9"
        '
        'btnSZ
        '
        Me.btnSZ.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnSZ.Location = New System.Drawing.Point(28, 116)
        Me.btnSZ.Name = "btnSZ"
        Me.btnSZ.Size = New System.Drawing.Size(88, 24)
        Me.btnSZ.TabIndex = 5
        Me.btnSZ.Text = "S to Z"
        '
        'btnMR
        '
        Me.btnMR.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnMR.Location = New System.Drawing.Point(28, 84)
        Me.btnMR.Name = "btnMR"
        Me.btnMR.Size = New System.Drawing.Size(88, 24)
        Me.btnMR.TabIndex = 4
        Me.btnMR.Text = "M to R"
        '
        'btnGL
        '
        Me.btnGL.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnGL.Location = New System.Drawing.Point(28, 52)
        Me.btnGL.Name = "btnGL"
        Me.btnGL.Size = New System.Drawing.Size(88, 24)
        Me.btnGL.TabIndex = 3
        Me.btnGL.Text = "G to L"
        '
        'btnAF
        '
        Me.btnAF.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnAF.Location = New System.Drawing.Point(28, 20)
        Me.btnAF.Name = "btnAF"
        Me.btnAF.Size = New System.Drawing.Size(88, 24)
        Me.btnAF.TabIndex = 2
        Me.btnAF.Text = "A to F"
        '
        'lblView
        '
        Me.lblView.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblView.Location = New System.Drawing.Point(16, 244)
        Me.lblView.Name = "lblView"
        Me.lblView.Size = New System.Drawing.Size(72, 16)
        Me.lblView.TabIndex = 3
        Me.lblView.Text = "Total Count :"
        '
        'lblView1
        '
        Me.lblView1.Location = New System.Drawing.Point(96, 244)
        Me.lblView1.Name = "lblView1"
        Me.lblView1.Size = New System.Drawing.Size(92, 16)
        Me.lblView1.TabIndex = 4
        '
        'frmView
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(542, 274)
        Me.Controls.Add(Me.lblView1)
        Me.Controls.Add(Me.lblView)
        Me.Controls.Add(Me.GroupBox1)
        Me.Controls.Add(Me.lvwReports)
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.Name = "frmView"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual
        Me.Text = "Select Master Crystal Reports File"
        Me.GroupBox1.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region
#Region " Initialize Listview and popuate with CR Reports "
    Private Sub InitializeListview()
        Cursor.Current = Cursors.WaitCursor

        OpenDBSqlConnection()
        Me.Width = 550
        Me.Text = "Customer List"
        lvwReports.Columns.Add("Number", 70, HorizontalAlignment.Right)
        lvwReports.Columns.Add("Customer List", 310, HorizontalAlignment.Left)
        If sTableName = "" Then
            sTableName = "MYTABLE"
        End If
        CustomerNames(sTableName)
        lvwReports.Sorting = SortOrder.Ascending
        lvwReports.View = View.Details
        Cursor.Current = Cursors.Default
    End Sub
    Public Sub CustomerNames(ByVal sTableName As String)
        Dim myDataRow As DataRow
        Dim DSList As New DataSet
        Dim iCounter As Short = 0

        sSQL = ""
        sSQL = "SELECT Name, ID FROM " & sTableName
        Try
            Dim TblAdapter = New SqlDataAdapter(sSQL, Connect)   'FOR SQL Server
            TblAdapter.Fill(DSList)

            For Each myDataRow In DSList.Tables(0).Rows
                With lvwReports
                    .Items.Add(myDataRow("ID").ToString())
                    .Items(iCounter).SubItems.Add(UCase(myDataRow("Name").ToString()))
                    iCounter += 1
                End With
            Next
            With lvwReports
                .Sorting = SortOrder.Ascending
                .View = View.Details
                .MultiSelect = True
            End With
            Me.lblView1.Text = CStr(iCounter)
        Catch Exp As SystemException
            MsgBox(Exp.Message & " CustomerNames Procedure Error", _
                    MsgBoxStyle.Critical, "Load Report Error")
            Cursor.Current = Cursors.Default
        End Try
    End Sub
    Private Sub btnAF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAF.Click, btnGL.Click, btnMR.Click, btnSZ.Click, btn09.Click
        Dim myDataRow As DataRow
        Dim DSList As New DataSet
        Cursor.Current = Cursors.WaitCursor
        Dim iCounter As Short = 0

        OpenDBSqlConnection()

        sSQL = ""

        Cursor.Current = Cursors.WaitCursor
        Try
            lvwReports.Clear()
            With lvwReports
                lvwReports.Columns.Add("Customer List", 310, HorizontalAlignment.Left)
                lvwReports.Columns.Add("Number", 70, HorizontalAlignment.Right)
                .MultiSelect = True
            End With
            sSQL = "SELECT Name, ID FROM " & sTableName & " "
            Select Case sender.Name
                Case "btnAF"
                    sSQL += "WHERE LEFT(Name, 1) BETWEEN 'A' AND 'F' "
                Case "btnGL"
                    sSQL += "Where LEFT(Name, 1) between 'G' and 'L' "
                Case "btnMR"
                    sSQL += "WHERE LEFT(Name, 1) between 'M' and 'R' "
                Case "btnSZ"
                    sSQL += "WHERE LEFT(Name, 1) between 'S' and 'Z' "
                Case "btn09"
                    sSQL += "WHERE LEFT(Name, 1) between '0' and '9' "
            End Select
            sSQL += "ORDER BY Name"
            Dim TblAdapter = New SqlDataAdapter(sSQL, Connect)   'FOR SQL Server
            TblAdapter.Fill(DSList)

            For Each myDataRow In DSList.Tables(0).Rows
                With lvwReports
                    .Items.Add(UCase(myDataRow("Name").ToString()))
                    .Items(iCounter).SubItems.Add(myDataRow("ID").ToString())
                    iCounter += 1
                End With
            Next
            bAlpha = True
            With lvwReports
                .Sorting = SortOrder.Ascending
                .View = View.Details
                .MultiSelect = True
            End With
            Me.lblView1.Text = CStr(iCounter)
        Catch Exp As SystemException
            MsgBox(Exp.Message & " Button Click Error", _
                    MsgBoxStyle.Critical, "Load Report Error")
            Cursor.Current = Cursors.Default
        End Try
        Cursor.Current = Cursors.Default
    End Sub
    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        ListNames()
        Me.Close()
    End Sub
#End Region
    Private Sub frmView_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Location = New Point(250, 100)
    End Sub
    Private Sub lvwReports_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles lvwReports.KeyPress
        Dim KeyAscii As Short = Asc(e.KeyChar)

        Select Case KeyAscii
            Case System.Windows.Forms.Keys.Back
            Case 13
                e.Handled = True
                SendKeys.Send("{TAB}")
            Case Is = 32
                KeyAscii = 0
            Case 48 To 57, 8
                Exit Sub
            Case Else
                e.Handled = True
        End Select
    End Sub
    Private Sub lvwReports_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwReports.DoubleClick
        Me.Height = 255
        Me.Width = 380
        lvwReports.MultiSelect = False
        ListNames()
        Me.Close()
    End Sub
    Private Sub ListNames()
        Dim i As Short

        If lvwReports.SelectedItems.Count = 0 Then Exit Sub
        btnOK.Enabled = True
        ReDim arrCunaID(lvwReports.SelectedItems.Count - 1)
        'Gobal counter for single and muti. hand picked numbers (customers)
        iCounterID = lvwReports.SelectedItems.Count
        'Make Array for Regular Addresses Per Customer List
        For i = 0 To lvwReports.SelectedItems.Count - 1
            Try
                If bAlpha = True Then
                    arrID(i) += lvwReports.SelectedItems.Item(i).SubItems(1).Text
                Else
                    arrID(i) += lvwReports.SelectedItems.Item(i).Text
                End If
            Catch Exp As SystemException
                If arrID(i) = "" Then
                    'Recheck database data
                    arrID(i) = CheckData(lvwReports.SelectedItems.Item(i).Text)
                Else
                    MsgBox("Reg. Address ... Button Click Error", MsgBoxStyle.Critical, "Load Report Error")
                End If
                Cursor.Current = Cursors.Default
            Catch Exp As Exception
                MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
            End Try
            Cursor.Current = Cursors.Default
        Next
        bAlpha = False
        Cursor.Current = Cursors.Default
    End Sub
    Private Function CheckData(ByVal sName As String)
        Dim myDataRow As DataRow
        Dim DSTableList As New DataSet
        Dim sDataName As String

        Cursor.Current = Cursors.WaitCursor
        Dim iCounter As Short = 0
        sSQL = ""

        OpenDBSqlConnection()

        Cursor.Current = Cursors.WaitCursor
        Try
            If sTableName = "" Then
                sTableName = "MYTABLE"
            End If

            sSQL = ""
            sSQL = "SELECT Name, ID FROM " & sTableName & " "
            sSQL = sSQL & " Where Name = '" & sName & "' "
            sSQL = sSQL & " ORDER BY Name"

            Dim TblAdapter = New SqlDataAdapter(sSQL, Connect)        'FOR Sql Server
            'Dim TblAdapter = New Odbc.OdbcDataAdapter(sSQL, SyConnect) 'FOR SyBase Server
            TblAdapter.Fill(DSTableList)

            For Each myDataRow In DSTableList.Tables(0).Rows
                sName = myDataRow("ID").ToString()
                sDataName = UCase(myDataRow("Name").ToString())
            Next
            CheckData = sName
        Catch Exp As SystemException
            MsgBox(Exp.Message & "     No  Number for " & sDataName, _
                    MsgBoxStyle.Critical, "Load Report Error")
            Cursor.Current = Cursors.Default
        End Try
        Cursor.Current = Cursors.Default
    End Function
    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    <STAThread()> Public Shared Sub Main()
        Application.Run(New frmView)
    End Sub

End Class


'MOD CLASS

Imports System.IO
Imports System.Data
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Data.SqlClient

Module modClass

     Public arrID() As String      
    Public iCounter As Short
 
 '**** Server Connection Vars *********
    Public sDBServer As String = "MYSERVER"
    Public sUSERid As String = "USERID"
    Public sDBName As String = "DATABASE"
    Public sDBPass As String = ""
    Public Connect As SqlConnection
    Public SyConnect As Odbc.OdbcConnection
    Public sSQL As String



   Public Sub OpenDBSqlConnection()
        If Len(sDBPass) = 0 Then
            sDBPass = ""
        End If
        Try
            Connect = New SqlConnection("Initial Catalog=" & sDBName & ";Data Source=" & sDBServer & ";User ID=" & sUSERid & ";password=" & sDBPass & ";")
            Connect.Open()
            Connect.Close()
        Catch Ex As Exception
            MsgBox("Exception: " & Ex.Message & "  " & Ex.ToString, MsgBoxStyle.Critical)
            Cursor.Current = Cursors.Default
        End Try
    End Sub


End Module


I think I have all the global vars in there, but I might have missed one.
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question