Santry Technology Solutions, Content Management, DotNetNuke, SharePoint Consulting
Register | Login
Friday, November 21, 2008

Sections
  
About Us
  
Partners
Downloads
  
 WWWCoder.com Resource Directory

Extending the DataGrid Control
7/3/2004 8:06:09 AM

This article covers how you can extend the DataGrid control. Instead of building a control from scratch, just add some new functionality to existing controls, we'll show you how.

Introduction:

In this article, I will explain how to extend the DataGrid class to provide some new functionalities. Building new web controls from scratch is not the best solution in most of cases, just adding some new functionalities to existing .NET Web controls will save you time and provide more stability. In addition, they'll be more compatible with any new versions of .NET framework.

Functionalities:

  • Add the total number of rows in the DataGrid footer.
  • Add Serial column

Source Code:

            Let's explain the code now step by step, first we have to create the class that will extend the DataGrid class:

      using System;
     
using
System.Web.UI;
     
using
System.Web.UI.WebControls;
     
using
System.ComponentModel;
     
using
System.Collections ;
     
using
System.Data;
 
      [assembly:TagPrefix("BNaffa.Web.Ui.WebControls","ExtendedDG")]
 

     
namespace
BNaffa.Web.UI.WebControls
            {
      [    
       DefaultProperty("ShowNoRows"),    
 ToolboxData("<{0}:ExtendedDG runat=server></{0}:ExtendedDG>")
      ]
      public class ExtendedDG :
DataGrid
      {
     
// strings constants represent the view state indexes
            const string SHOW_NO_ROWS="ShowNoRows";
            const string NO_ROWS="NoOfRows";
            const string SHOW_SERIAL ="ShowSerial";

                 

     
// Constructor
     
public
ExtendedDG():base()
      {
      }
                       
     
// Properties & Methods go here
      }

Then, we'll add the following two properties:  

  • ShowNoRows [true/false]
  • ShowSerial [true/false]

         [Bindable(true),
             Category("Appearance")
            ]
            public bool
ShowNoRows
            {
                 
get
                  {
                  return Convert.ToBoolean(ViewState[SHOW_NO_ROWS]);
                  }
 
                 
set
                  {
                        ViewState[SHOW_NO_ROWS]= value;
                  }
            }
 
            [Bindable(true),
             Category("Appearance")
            ]
            public bool
ShowSerial
            {
                 
get
                  {
                  return Convert.ToBoolean(ViewState[SHOW_SERIAL]);
                  }
 
                 
set
                  {
                        ViewState[SHOW_SERIAL]= value;
                  }
            }
                   

 This private function  will check if we are in the design mode or in runtime mode:                                   

         private bool IsInDesignMode()
            {
                  if (this.Site != null)
                        return this.Site.DesignMode;
                  return false;
                 
            }

Total Number Of Rows Functionality:

Now we want to know the number of rows for current DataSource. Ok, how do we get that? One of solutions is to cast the data source property for the data grid to a data set or data table and get the number of rows. But I don't prefer this way!! I will give you a short way without casting cost.

We will override the method CreateColumnSet which be called when you invoke the method DataBind:

protected override ArrayList CreateColumnSet
          
(PagedDataSource dataSource, bool useDataSource)

      {
      if (dataSource != null)
            ViewState[NO_ROWS] = dataSource.DataSourceCount;
            return base.CreateColumnSet (dataSource, useDataSource);
      }

As you see, this function will receive an object of type PagedDataSource, this object contains a DataSourceCount property,

Then we will save this number in the ViewState collection. Using this method, you can get the data source count without casting and with any type of data sources [DataSet, DataView, DataTable, ArrayList, etc...]

Now we will override the method OnItemCreated, to add the total number of rows in the DataGrid footer:

protected override void OnItemCreated(DataGridItemEventArgs e)
            {
                  base.OnItemCreated (e);
 
                  if (!IsInDesignMode())
// Only in Runtime Mode
                  {
                        if (e.Item.ItemType == ListItemType.Footer)
                        {
                              if(ShowNoRows && ShowFooter )
                              {
                              if(e.Item.Cells.Count > 0)
                              {
                              e.Item.Cells[0].Text = ViewState[NO_ROWS] + " Rows.";
                              }
                              }
                        }
                  }    
            }

Serial Column Functionality:

Before writing the serial number to the DataGrid, we have to add a template column for the serial field, so we must have this class which implements the interface ITemplate and the method InstantiateIn:

      public class MyColumn:ITemplate
            {
                  public void InstantiateIn ( Control container )
                  {
                       
                  }    
            }

We will add this serial column in the OnOnit Method which handles the DataGrid initiation process:           

      protected override void OnInit(EventArgs e)
            {
                  base.OnInit (e);
                  if (! IsInDesignMode())
// Only in Runtime Mode
                  {
                        TemplateColumn tmpCol new TemplateColumn();
                        MyColumn myCol   new MyColumn();
                        tmpCol.ItemTemplate = myCol;
                        this.Columns.Add(tmpCol);                      
                  }
      }

Now we have to add the serials to the new Column, we will add another fragment code to the previous overridden method OnItemCreated, so it will be like this:

protected override void OnItemCreated(DataGridItemEventArgs e)
            {
                  base.OnItemCreated (e);
                  if (!IsInDesignMode())
// Only in Runtime Mode
                  {
                        if (e.Item.ItemType == ListItemType.Footer)
                        {
                              if(ShowNoRows && ShowFooter )
                              {
                              if(e.Item.Cells.Count > 0)
                              {
                              e.Item.Cells[0].Text = ViewState[NO_ROWS] + " Rows.";
                              }
                              }
                        }
                        if (e.Item.ItemType == ListItemType.Header)
                        {
                              if(ShowSerial && ShowHeader )
                              {
                                    e.Item.Cells[0].Text = "#";
                              }
                        }

                        else
if (e.Item.ItemType == ListItemType.Item ||
                        e.Item.ItemType
== ListItemType.AlternatingItem )
                        {
                        if(ShowSerial)
                        {

                        e.Item.Cells
[0].Text= (e.Item.ItemIndex +
                        (this.PageSize*this.CurrentPageIndex ) + 1 ).ToString();
                        }
                        }
                  }    
}
                                 

The important thing here is the equation that calculates the current row number, we will consider the current page index to work properly with DataGrid paging (e.Item.ItemIndex + (this.PageSize * this.CurrentPageIndex ) + 1 )    

Now you can compile the project and use the assembly to add new control to your toolbox tab in Visual Studio.NET., and you can use the new DatarGrid and set these properties ShowNoSerial, ShowSerial to true to show this functionality.

 

 

Download Source Code  and Sample!  

About Author:

Bashar Naffa’, MCSD/MCAD.

I have worked in .NET since Beta, and now digging deep inside .NET Framework 2.0!


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 9/4/2008 5:30:39 PM by Anonymous
Comments:
Left on 3/30/2006 5:40:05 AM by Anonymous
Comments: I want to know if we are overriding the OnItemCreated event when it will be triggered
Left on 4/13/2005 6:58:39 AM by Anonymous
Comments: Thank You Bashar!
Left on 3/4/2005 4:00:52 PM by Anonymous
Comments: Great article. Keep it up. Visual Basic .NET is meant for girls and girly men. C# is for real men. For those of you who want it in VB.NET, go learn C# and object oriented programming (since VB guys code in VB.NET like they use to code in VB before) or else take a hike.
No ratings available.
Left on 2/6/2005 8:34:12 AM by Anonymous
Comments: Good one,you can do more.

Left on 2/3/2005 9:30:58 PM by Anonymous
Comments: Useful form 2 points the datagrid extension and the toolbox assembly...thanks
No ratings available.
Left on 2/3/2005 1:58:59 PM by Anonymous
Comments: you people whinning about no vb code should just write it yourselves
Left on 1/8/2005 6:25:42 AM by Anonymous
Comments: hope to see above code done in visual basic.net
best regard

No ratings available.
Left on 1/8/2005 6:24:10 AM by Anonymous
Comments: According to the number of
developers using vb.net, i hope to see the above code done in visual basic.net.
thanks.
No ratings available.
Left on 12/1/2004 5:07:38 PM by Anonymous
Comments: Get a real job
Left on 10/31/2004 4:13:40 AM by Anonymous
Comments: thank u !!!
Left on 10/25/2004 5:31:14 PM by Anonymous
Comments: very very very Poor
No ratings available.
Left on 10/11/2004 5:07:16 AM by Anonymous
Comments: try this
http://www.makeitscroll.com/

it's not free :(:(
Left on 10/8/2004 8:43:19 AM by Anonymous
Comments: Very helpful article!
Do you have any trick to Freeze columns in datagrid? I have 40 columns in the datagrid and want to use paging as well as scrollbars but while scrolling, need to freeze first three columns. Any idea how this can be done with the trick. Thanks.
No ratings available.
Left on 9/12/2004 8:55:35 AM by Anonymous
Comments: to contact me:
bashar naffa'
b_naffa@hotmail.com
Left on 8/30/2004 6:34:59 AM by Anonymous
Comments: Great article!
Left on 8/30/2004 2:26:17 AM by Anonymous
Comments: Hello , Great Job
can you put your email so that we can contact you
bilal okour, Arabilla.net
Left on 7/19/2004 2:41:29 PM by Anonymous
Comments: it need visual studio 2003, try to open the project file instead of solution, then save the new solution

Bashar Naffa
Left on 7/15/2004 1:49:58 AM by Anonymous
Comments: I am unable to open the solution
Left on 7/5/2004 1:55:01 PM by Anonymous
Comments: good Luck
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970