Saturday, July 14, 2012

Grouping Gridview cells in ASP.NET

Grouping cells in a Gridview is important to merge related items. But, merging related items has not been easy from the code-behind. Thankfully, using Jquery merging of gridview cells can be done effortlessly.


Add reference to the jquery library from the Microsoft Content Delivery Network or Google Libraries API,

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
(or alternatively)
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js"></script>


And in the body place two Gridviews, one for listing the products with no grouping and the other for listing the products with grouping.

Default.aspx
<script type="text/javascript">

function GroupGridViewCells(gridviewId) {

            var rowNum = $(gridviewId + " tr").length;

            var colNum = $(gridviewId + " tr:eq(0)>th").length;

            var cell = null;

            var previouscell = null;

            // Begin to loop from the second row to the end
            for (var col = 0; col < colNum; ++col) {

                for (var row = 1; row < rowNum; ++row) {

                    cell = $(gridviewId + " tr:eq(" + row + ")>td:eq(" + col + ")").first();

                    if (row == 1) {
                        previouscell = $(gridviewId + " tr:eq(" + row + ")>td:eq(" + col + ")").first();
                        previouscell.attr("rowspan", "1");
                    }
                    else {

                        if (cell.html() == previouscell.html()) {

                            previouscell.attr("rowspan", parseInt(previouscell.attr("rowspan") + 1));
                            cell.css("display", "none");
                        }
                        else {

                            previouscell = $(gridviewId + " tr:eq(" + row + ")>td:eq(" + col + ")");
                            previouscell.attr("rowspan", "1");
                            previouscontent = previouscell.html();
                        }
                    }
                }
            }
        }

$(document).ready(function () {
        GroupGridViewCells("#groupedGridView");
}
</script>

<div>
        <table>
            <tr>
                <td style="padding: 20px">
                    <h3>
                        GridView(without grouping)</h3>
                    <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
                        OnPageIndexChanged="GridView1_PageIndexChanged"
                        OnPageIndexChanging="GridView1_PageIndexChanging">
                        <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        <RowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    </asp:GridView>
                </td>
                <td style="padding: 20px">
                    <h3>
                        GridView(with grouping)</h3>
                    <asp:GridView ID="groupedGridView" runat="server" AllowPaging="True"
                        OnPageIndexChanged="groupedGridView_PageIndexChanged"
                        OnPageIndexChanging="groupedGridView_PageIndexChanging">
                        <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        <RowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>

Default.aspx.cs
using System.Data;

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindSortedProducts(GridView1);
                BindSortedProducts(groupedGridView);
            }
        }

private void BindSortedProducts(GridView gridView)
        {
            const string ProductsDataViewStateId = "ProductsData";
            DataTable dt = ViewState[ProductsDataViewStateId] as DataTable;

            if (dt == null)
            {
                dt = new DataTable();
                dt.Columns.Add("Product Name", typeof(string));
                dt.Columns.Add("Category", typeof(int));
                dt.Columns.Add("Price", typeof(double));
                Random r = new Random();

                for (int i = 1; i <= 100; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["Product Name"] = "Product" + r.Next(1, 5);
                    dr["Category"] = Convert.ToInt32(r.Next(1, 5));
                    dr["Price"] = Convert.ToDouble(Math.Round(r.NextDouble() * 100 + 25, 2));
                    dt.Rows.Add(dr);
                }

                ViewState[ProductsDataViewStateId] = dt;
            }

            // Sort by ProductName and Category
            dt.DefaultView.Sort = "Product Name,Category";
         
            gridView.DataSource = dt;
            gridView.DataBind();
        }


        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            generalGridView.PageIndex = e.NewPageIndex;
        }

        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            BindSortedProducts(GridView1);
        }

        protected void groupedGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            groupedGridView.PageIndex = e.NewPageIndex;
        }

        protected void groupedGridView_PageIndexChanged(object sender, EventArgs e)
        {
            BindSortedProducts(groupedGridView);
        }

No comments:

Codeigniter Shield - Account Activation & Two-Factor Authentication

Account Activation & Two-Factor Authentication