Automatic ListView Grouping

3:49 AM

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

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 dont 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 usefull to someone.

Code:

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:



3 comments:

{ daydreamer } at: July 22, 2011 at 10:07 AM said...
This comment has been removed by the author.
{ daydreamer } at: July 22, 2011 at 10:11 AM said...
This comment has been removed by the author.
{ Administrador do Blog } at: July 14, 2017 at 1:35 PM said...

MY FRIENDSHIP YOU SAVE MY LIFE, YOU DO NOT KNOW THE DIFFICULTY YOU HAVE FINDED THAT. THANK YOU FOR SHARING YOUR KNOWLEDGE. ETERNALLY GRATEFUL!

Post a Comment