Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello dear CPers,

I have a gridview, that I bind from a list. What I want is how I can apply a custom grouping in this gridview? I dont need code but I need some advise how I can implement this. What I mean by custom grouping; user will select the rows that they desire to group so grouping by columns will not work. I will be glad if someone show me a path accomplishing this. Thanks.
Posted

I hope this sample will help you well. GridView: Creating groups and summaries[^]
 
Share this answer
 
Genric method for Grouping the rows in gridview

void GroupGridView(GridViewRowCollection gvrc, int startIndex, int total)
    {
        if (total == 0) return;
        int i, count = 1;
        ArrayList lst = new ArrayList();
        lst.Add(gvrc[0]);
        var ctrl = gvrc[0].Cells[startIndex];
        for (i = 1; i < gvrc.Count; i++)
        {
            TableCell nextCell = gvrc[i].Cells[startIndex];
            if (ctrl.Text == nextCell.Text)
            {
                count++;
                nextCell.Visible = false;
                lst.Add(gvrc[i]);
            }
            else
            {
                if (count > 1)
                {
                    ctrl.RowSpan = count;
                    GroupGridView(new GridViewRowCollection(lst), startIndex + 1, total - 1);
                }
                count = 1;
                lst.Clear();
                ctrl = gvrc[i].Cells[startIndex];
                lst.Add(gvrc[i]);
            }
        }
        if (count > 1)
        {
            ctrl.RowSpan = count;
            GroupGridView(new GridViewRowCollection(lst), startIndex + 1, total - 1);
        }
        count = 1;
        lst.Clear();
    }


You have to pass 3 parameters:
gvrc: GridView Rows
startIndex: index of first column to be grouped(where to start grouping).
total: total number of columns to be grouped.


How to Use:

Before using this method, Make sure data is sorted in same order in which they are to be grouped. Bind the gridview and Pass the gridview rows, start index and total number of columns to be grouped in GroupGridView method and enjoy it.
?
1
2
3

GridView1.DataSource = GetDataTable();
GridView1.DataBind();
GroupGridView(GridView1.Rows, 0, 3);

The above code will group first 3 columns of gridview.

Hope, It’ll save your time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900