[Latest News][6]

color C# keyword in RichTextBox
Highlight C# keyword in RichTextBox
How to Merge DataGridView Columns
How to Merge DataGridView Rows
How to Merge GridView Columns
How to Merge GridView Rows
how to send sms
Make SMS Gateway using C#.net
Merge DataGridView Columns
Merge DataGridView Rows
Merge GridView Columns
Merge GridView Rows
read sms
Send and Read SMS through a GSM Modem using AT Commands
send or read sms
sent sms
Syntax Highlighting in RichTextBox using C#

How to Merge GridView Rows (Cells with Equal Values)



How to Merge GridView Rows (Cells with Equal Values)



There are a lot of methods in the Internet solving the problem of how to merge GridView rows if neighbour cells show equal values. My approach is not the first; however, I think, it is rather universal and very short - less than 20 lines of code. 




The algorithm is simple: to bypass all the rows, starting from the second at the bottom, to the top. If a cell value is the same as a value in the previous (lower) row then to increase RowSpan and to make invisible the lower cell, and so forth. 

The code that merges cells is very short:

public class GridDecorator

{

    public static void MergeRows(GridView gridView)

    {

        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)

        {

            GridViewRow row = gridView.Rows[rowIndex];

            GridViewRow previousRow = gridView.Rows[rowIndex + 1];



            for (int i = 0; i < row.Cells.Count; i++)

            {

                if (row.Cells[i].Text == previousRow.Cells[i].Text)

                {

                    row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : previousRow.Cells[i].RowSpan + 1;

                    previousRow.Cells[i].Visible = false;

                }

            }

        }

    }
}

The last action is to add an OnPreRender event handler for the GridView: 

protected void gridView_PreRender(object sender, EventArgs e)

{

    GridDecorator.MergeRows(gridView);

}
  

About Author Mohamed Abu 'l-Gharaniq

when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries.

No comments:

Post a Comment

Start typing and press Enter to search