Wednesday, May 14, 2008

Add custom row to GridView

   1: public partial class _Default : System.Web.UI.Page
   2: {
   3:     static int pgSize;
   4:  
   5:     protected void Page_Load(object sender, EventArgs e)
   6:     {
   7:         if(!Page.IsPostBack)
   8:               pgSize = 0;
   9:     }
  10:  
  11:     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  12:     {
  13:         if (e.Row.RowType == DataControlRowType.DataRow)
  14:         {
  15:             TableCell tCell = new TableCell();
  16:             // create image
  17:             Image img = new Image();
  18:             img.ImageUrl = "subheader.jpg";
  19:             // add the image to the cell
  20:             tCell.Controls.Add(img);
  21:            
  22:             GridView gView = (GridView)sender;
  23:             // set the colspan to occupy the other cells in the row
  24:             int colSpan = gView.Columns.Count;
  25:             tCell.Attributes["ColSpan"] = colSpan.ToString();
  26:  
  27:             GridViewRow gRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
  28:             // add the cells to the gridviewrow
  29:             gRow.Cells.Add(tCell);
  30:  
  31:             Table tbl = (Table)e.Row.Parent;
  32:  
  33:             // set the pagesize initially to the pagecount/2
  34:             // in our case it is 10/2 = 5. So the first image will
  35:             // displayed after the 5th row.
  36:             if(pgSize == 0)
  37:                 pgSize = GridView1.PageCount / 2;
  38:  
  39:             // This step is performed so that we can display the image only after every
  40:             // 5, 15, 25 ,35 rows and so on ...
  41:             // The logic is not perfect but will give you the idea
  42:             if (Convert.ToDouble(e.Row.DataItemIndex + 1) / Convert.ToDouble(pgSize) == 1.0)
  43:             {
  44:                 tbl.Controls.AddAt(gView.Controls[0].Controls.Count, gRow);
  45:                 // add 10 to the pgsize so that the image can be displayed
  46:                 // at rows 5, 15, 25 and so on..
  47:                 pgSize = pgSize + 10;
  48:             }
  49:         }
  50:     }
  51: }

2 comments:

  1. Great idea. This really solves my problem

    ReplyDelete
  2. I too added a image dynamically in gridview as it is shown in the example. But mine is a custom grid view, when i try to show a image the width of that image goes beyond the grid view width.
    It seems as if some colspan is the problem but though i changed the colspan it is not responding to it. Please help me in this issue.

    ReplyDelete