Search code examples
c#winformsdatagridviewgrouping

DataGridView with Groupheaders spanning the entire row


I was wondering if there was any way of getting the Datagridview to group it's line by a Property in it's datasource (Not used in the columns) and add the grouping header as well. I've added a picture for reference.

enter image description here

I did override the Defaultcell style to have alternatives (like "No Nuts") available, and I know i can "just group the datasource" to have it sorted/grouped. however I would like to have these groupheaders as well.

Any help would be appreciated!


Solution

  • So I made another layer on top of the BindingList from the datasource and put this as the Datasource.

        public class GroupedBindingList : BindingList<OrderlineModel>
    {
       
    
         public BindingList<OrderlineModel> OriginalList { get; set; }
            public SortedDictionary<int, BindingList<OrderlineModel>> GroupedOrderlineDict;
            public GroupedBindingList(BindingList<OrderlineModel> list)
            {
                OriginalList = list;
                GroupedOrderlineDict = new();
                GroupBy();
                OriginalList.ListChanged += OriginalList_ListChanged;
            }
            protected GroupedBindingList() { }
        }
    

    I could then add the grouby function and use a extension of the lines in the datasource object to determen if the line I was dealing with a header or a normal line. I also hooked onto the original list changed event to refresh and regroup the grid given an item was added or reset. Made this the center piece of a user control and it works perfectly.

    Hope this helps someone else!