Automatic ListView Grouping

Lets say you have lots of data your listview. Now you want to Group This data According to a Particular Subitem.

For Example:

Suppose i have some books data in my ListView.
this listview items contains Author name and Books Title.

And there are 2000 Books in list view.

Now i want to group the data in listview according to the Authors.

Now lets say there are 50 Unique Authors , meaning we will have to create 50 Groups in listview.

this seem hectic, and i don’t know if there is any inbuilt function to automatically group this items, but i have created mine To automatically do the above.

Hope it becomes useful to someone.

public void GroupListView(ListView lstV, int SubItemIndex) {
 bool flag = true;

 foreach(ListViewItem l in lstV.Items) {
  string strmyGroupname = l.SubItems[SubItemIndex].Text;

  foreach(ListViewGroup lvg in lstV.Groups) {
   if (lvg.Name == strmyGroupname) {
    l.Group = lvg;
    flag = false;
   }
  }

  if (flag == true) {
   ListViewGroup lstGrp = new ListViewGroup(strmyGroupname, strmyGroupname);
   lstV.Groups.Add(lstGrp);
   l.Group = lstGrp;
  }

  flag = true;
 }
}

How To Use The Code:
Lets say the author’s sub item’s index is 1 and listview name is LstBooks then call the function like:

GroupListView(LstBooks,1);

Vb.net Version:

Public Sub GroupListView(ByVal lstV As ListView, ByVal SubItemIndex As Int16)
Dim flag As Boolean = True
For Each l As ListViewItem In lstV.Items

Dim strmyGroupname As String = l.SubItems(SubItemIndex).Text

For Each lvg As ListViewGroup In lstV.Groups

If lvg.Name = strmyGroupname Then
l.Group = lvg
flag = False
End If

Next

If flag = True Then
Dim lstGrp As New ListViewGroup(strmyGroupname, strmyGroupname)
lstV.Groups.Add(lstGrp)
l.Group = lstGrp
End If

flag = True

Next
End Sub

Output:

listgroup

 

3 thoughts on “Automatic ListView Grouping

  1. Mp3 Tagger Zortam Mp3 Media Studio is all-in-one Mp3 application suite. It has several modules such us Zortam Mp3 Auto Tagger, Mp3 Organizer, ID3 Tag Editor, Mp3 Player, Mp3 Normalizer, CD Ripper, Mp3 to Wav converter. With Zortam Mp3 Media Studio you can batch auto tag your Mp3 files using Zortam database. Batch auto tag process download Cover Art, Lyrics and other metadata and automatically tags your Mp3 files.

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami