Thursday, August 8, 2013

Gridview_DataBound Event




The DataBound event fires when all the databinding for the Gridview is finished, so that you could do, say, subtotals of all the rows in the Gridview at that point as you know there aren't going to be any more rows in the view. You call it like any other event, set the attribute in your markup and put the code in your code-behind:
    /// <summary>
    /// Executes when the databinding is complete
    /// </summary>
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        //I'll use it to show which set of Rows I'm showing in the page.
        GridView1.ShowFooter = true;
        //Similar to: GridView1.FooterRow.Visible = true
        //Stretching the first cell to fill the whole FooterRow:
        //Removing all non needed cells,
        // from the end to start
        // (so that the Cells collection is not recreated with every Removal).
        for (int cellNum = GridView1.Columns.Count - 1; cellNum > 0; cellNum--)
        {
            GridView1.FooterRow.Cells.RemoveAt(cellNum);
        }
        GridView1.FooterRow.Cells[0].ColumnSpan = GridView1.Columns.Count;
        GridView1.FooterRow.Cells[0].HorizontalAlign = HorizontalAlign.Center;
        int startIndex = GridView1.PageIndex != GridView1.PageCount - 1 ?
        //Not in last page.
        GridView1.PageSize * GridView1.PageIndex
        //GridView1 Rows Count is Count of the Rows of the current page, so,
            // unless Paging is Disabled, this is not total Rows Count.
            //gridViewTotalCount is declared and assigned just after this method.
        : gridViewTotalCount - GridView1.PageSize + GridView1.Rows.Count;
        GridView1.FooterRow.Cells[0].Text =
            string.Format
                ("Showing Employees {0} to {1} of {2}",
                startIndex + 1,
                startIndex + GridView1.Rows.Count, gridViewTotalCount);
    }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More