Automatic ListView Grouping

sandeepparekh9 0 Tallied Votes 288 Views Share

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.


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);

and its done..

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;


            }
        }