Extending the DataGrid Control

原创 2004年08月30日 13:09:00

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.

 

table1extendeddatagrid.gif

table2extendeddatagrid.gif

 

Download Source Code  and Sample!  

Unity3D引擎扩展中的编辑器定制方法

Unity3D的方便之处在于,它很容易地扩展编辑器套件。每款游戏都对加工有着不同的需求,可以快速地以完全集成的方法来构建这些内容并极大地提升开发速度。 目前有大量复杂的软件包提供以基本Unity...
  • luyuncsd123
  • luyuncsd123
  • 2014年03月24日 00:51
  • 2334

MySQL中ib_logfile和ibdata1参数大小被修改后

1. 环境说明 RHEL 6.4 x86_64 + MySQL 5.5.37和MySQL 5.6.19 2. 案例:redo log文件(ib_logfile)大小参数被修改:innodb_log_...
  • HW_LiBo
  • HW_LiBo
  • 2014年09月12日 00:22
  • 18174

MongoDB安装及基本使用

MongoDB是一个使用C++编写的、开源的、面向文档的NoSQL(Not Only SQL)数据库,也是当前最热门的NoSql数据库之一。 NoSQL简介 NoSQL的意思是“不仅仅是SQL”,...
  • xiaoxing598
  • xiaoxing598
  • 2017年01月08日 17:11
  • 6077

Extending ASPX Panel Control to produce Rounded Corners

  • 2009年01月04日 14:05
  • 65KB
  • 下载

csharp: Data binding in WPF DataGrid control

  • geovindu1
  • geovindu1
  • 2015年07月13日 17:55
  • 692

电商系统Broadleaf文档翻译(七) – 扩展实体extending entities

原文标题:main services 原文出处:http://www.broadleafcommerce.com/docs/core/current/broadleaf-concepts/data-...
  • matthewei6
  • matthewei6
  • 2016年03月15日 19:59
  • 1289

14. 59. 3.从AbstractTableModel继承 Extending AbstractTableModel

import java.awt.BorderLayout; import java.awt.Container; import java.util.Calendar; import java.util...
  • youyigong
  • youyigong
  • 2011年10月20日 11:44
  • 689

Extending Python with C\C++ 实践问题

编写好Extending Python with C\C++的小程序后,用codeblocks编译出dll文件,放在python查找目录下,但调用PyErr_SetString后出现错误:undefi...
  • heiyeah09
  • heiyeah09
  • 2015年04月21日 13:46
  • 444

编写Python扩展(Extending Python with C or C++)

其实这是一篇译文,看官方文档的时候觉得不好对重点做标记,加上以后遗忘的时候看中文可以更快速的捡起来,所以在阅读的过程中就直接翻译出来记录在此了,借助于博客的一下编辑功能对重点做一些突出表现。 1. E...
  • xiarendeniao
  • xiarendeniao
  • 2013年07月19日 00:22
  • 4144

QT 国际化扩展所感 an extending QT Translator (自己实现翻译逻辑,编辑更方便)

QT中提供了支持国际化的QTranslator,
  • elfprincexu
  • elfprincexu
  • 2014年07月16日 13:05
  • 742
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Extending the DataGrid Control
举报原因:
原因补充:

(最多只允许输入30个字)