Using List View Groups

Hi experts,
Having problems with a list view in and cant get the groups to work.

Coming in is a datatable with Part number, order number, order qauntity.

I am trying to create groups in the listview to group the orders by part number.

 Public Sub PopulateListViewFromDt(ByVal Dt As DataTable)
        Dim Dtunique As New DataTable

'Find the unique part number list
        If Dt.Rows.Count > 0 Then
            Dtunique = Dt.DefaultView.ToTable(True, GroupName)
        End If

'Add a group for each item in the unique part number list
        For Each row As DataRow In Dtunique.Rows
            Dim LVG As New ListViewGroup
            With LVG
                .Name = row(GroupName)
                .Header = row(GroupName)
            End With

'Create the list view item for each item in the datatable.
           Dim LVG As ListViewGroup
            Dim LVI As New ListViewItem

' I would rather not do this step....I would like to create the group and assign an item to the group, since the group name is known.
            For Each Group In ListViewName.Groups
                If = row("PartNumber") Then
                    LVG = Group
                End If

            With LVI
                If row(ValidationCriteria) = True Then
                    .Checked = True
                End If

                For Each Col In Columns
                    If Col <> TopItem Then
                    End If

                .Name = row("PartNumber").ToString
                .Group = LVG
            End With


    End Sub

Open in new window

Thanks for the help in advance, I have read many help topics but I must be missing something.

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kerrymrAuthor Commented:
I dont understand how that is fundamentally different than what I did.

   .Group = LVG

Open in new window

BillSoftware EngineerCommented:
not sure what your code is doing. why don't you make it easy on yourself and sort the dataTable. it is a few easy steps. Follow the instructions in this link
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

kerrymrAuthor Commented:
I already filter the datatable to unique records of part number.
Then I use those unique part numbers to create list view groups.
So the question still stands, I created the groups how do I assign items to the groups?

        For Each Item As ListViewItem In ListViewName.Items
            Item.Group = ?????????????????

Open in new window

Are you wanting to accomplish something like this:

Form1.vb -
Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Public Class Form1
	ReadOnly parts = (From i In Enumerable.Range(0, 30)
					  Select New With
						  .ID = i,
						  .PartNumber = If(i Mod 5 = 0, 5050, If(i Mod 4 = 0, 4040, If(i Mod 3 = 0, 3030, If(i Mod 2 = 0, 2020, 1010)))),
						  .OrderNumber = $"OrderNumber{i}",
						  .OrderQuantity = i + 1 * 4
	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		ListView1.View = View.Details
	End Sub
End Class

Module Extensions
	Public Function ConvertToDataTable(Of T)(ByVal source As IEnumerable(Of T), Optional ByVal name As String = Nothing) As DataTable
		Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
		Dim table As DataTable = New DataTable(If(Not String.IsNullOrWhiteSpace(name), name, String.Empty))

		For i As Integer = 0 To properties.Count - 1
			Dim [property] As PropertyDescriptor = properties(i)
			If [property].PropertyType.IsGenericType AndAlso [property].PropertyType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then
				table.Columns.Add([property].Name, [property].PropertyType.GetGenericArguments()(0))
				table.Columns.Add([property].Name, [property].PropertyType)
			End If

		Dim values(properties.Count - 1) As Object
		For Each item As T In source
			For i As Integer = 0 To properties.Count - 1
				values(i) = properties(i).GetValue(item)

		Return table
	End Function

	Public Sub PopulateListViewFromDT(target As ListView, source As DataTable)
		If source IsNot Nothing AndAlso source.Rows.Count > 0 Then
			target.Columns.AddRange((From column In source.Columns.Cast(Of DataColumn) Select New ColumnHeader() With {.Name = column.ColumnName, .Text = column.ColumnName, .Width = 100}).ToArray())
			For Each row In source.AsEnumerable().Cast(Of DataRow)
				Dim group = target.Groups.Cast(Of ListViewGroup).Where(Function(x) x.Name = row("PartNumber")).SingleOrDefault()
				If group Is Nothing Then
					group = New ListViewGroup With {.Name = row("PartNumber"), .Header = row("PartNumber")}
				End If
				target.Items.Add(New ListViewItem((From item In row.ItemArray Select $"{item}").ToArray()) With {.Group = group})
		End If
	End Sub
End Module

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
			If disposing AndAlso components IsNot Nothing Then
			End If
		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.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.ListView1 = New System.Windows.Forms.ListView()
		Me.ListView1.Location = New System.Drawing.Point(13, 13)
		Me.ListView1.Name = "ListView1"
		Me.ListView1.Size = New System.Drawing.Size(655, 236)
		Me.ListView1.TabIndex = 0
		Me.ListView1.UseCompatibleStateImageBehavior = False
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(680, 261)
		Me.Name = "Form1"
		Me.Text = "Form1"

	End Sub

	Friend WithEvents ListView1 As ListView
End Class

Open in new window

Which produces the following output -Capture.PNG

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kerrymrAuthor Commented:
This looks very much like what I'm looking for.  
Give me some time to test and I'll advise if complete or additional questions.  
It does look very promising.

kerrymrAuthor Commented:
Thank you very much that did indeed do what I needed.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.