DataGrid Control in ASP.net

By: Dan Hurwitz and Jesse Liberty Emailed: 1680 times Printed: 2159 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The problem with predesigned user controls is typically that they are either simple and therefore too limited to do what you want, or they are powerful and therefore so complex that they are very difficult to learn. The DataGrid control attempts to overcome both of these constraints. Creating a simple DataGrid control couldn't be much easier, yet there is enough power and complexity to keep you quite busy tweaking and modifying the control to do exactly what you want.

To explore both the simplicity and the power of the DataGrid control, we'll use the process of successive approximation to get something working quickly and then to keep it working while we enhance it.

Displaying Data

In the first iteration, you'll create a DataGrid object and display some simple data. To get started, you need a data source, in this case an ArrayList that you'll populate with Bug objects. You will define the Bug class, and each Bug object will represent a single bug report. For now to keep it simple, you'll give the Bug class a few fields to hold representative information about a given code bug. Example 1 is the definition of the Bug class in C#; Example 2 is the same definition in VB.NET.

Example 1. The Bug class in C#
using System;

public class Bug
{
   // private instance variables
   private int bugID;
   private string title;
   private string reporter;
   private string product;
   private string version;
   private string description;
   private DateTime dateCreated;
   private string severity;
      
   // constructor
   public Bug(int id, 
      string title,        // for display
      string reporter,     // who filed bug
      string product, 
      string version, 
      string description,  // bug report
      DateTime dateCreated, 
      string severity)
   {
      bugID = id;                      
      this.title = title;              
      this.reporter = reporter;        
      this.product = product;          
      this.version = version;
      this.description = description;
      this.dateCreated = dateCreated;
      this.severity = severity;
   }

   // public read only properties
   public int BugID { get { return bugID; }}
   public string Title { get { return title; }}
   public string Reporter { get { return reporter; }}
   public string Product { get { return product;  }}
   public string Version { get { return version;  }}
   public string Description { get { return description; }}
   public DateTime DateCreated { get { return dateCreated; }}
   public string Severity { get { return severity; }}
}
Example 2. The Bug class in VB.NET
Public Class Bug
   Private _bugID As Int32
   Private _title As String
   Private _reporter As String
   Private _product As String
   Private _version As String
   Private _description As String
   Private _dateCreated As DateTime
   Private _severity As String

   Sub New(ByVal theID As Int32, _
   ByVal theTitle As String, _
   ByVal theReporter As String, _
   ByVal theProduct As String, _
   ByVal theVersion As String, _
   ByVal theDescription As String, _
   ByVal theDateCreated As DateTime, _
   ByVal theSeverity As String)

      _bugID = theID
      _title = theTitle
      _reporter = theReporter
      _product = theProduct
      _version = theVersion
      _description = theDescription
      _dateCreated = theDateCreated
      _severity = theSeverity
   End Sub

   Public ReadOnly Property BugID(  ) As Int32
      Get
         BugID = _bugID
      End Get
   End Property

   Public ReadOnly Property Title(  ) As String
      Get
         Title = _title
      End Get
   End Property

   Public ReadOnly Property Reporter(  ) As String
      Get
         Reporter = _reporter
      End Get
   End Property

   Public ReadOnly Property Product(  ) As String
      Get
         Product = _product
      End Get
   End Property

   Public ReadOnly Property Version(  ) As String
      Get
         Version = _version
      End Get
   End Property

   Public ReadOnly Property Description(  ) As String
      Get
         Description = _description
      End Get
   End Property

   Public ReadOnly Property DateCreated(  ) As String
      Get
         DateCreated = _dateCreated
      End Get
   End Property

   Public ReadOnly Property Severity(  ) As String
      Get
         Severity = _severity
      End Get
   End Property

End Class

The Bug class consists of nothing except a number of private members and read-only properties to retrieve these values. In addition, there is a constructor to initialize the values. The reporter member variable (_reporter) stores the name of the person reporting the bug, the product and version (_product and _version) are strings that represent the specific product that has the bug. The description field holds the full description of the bug, while title is a short summary to be displayed in the data grid.

The .aspx file simply creates a DataGrid within a form. The only attribute is the ID and, of course, runat="server", as you would expect in any ASP web control. The complete .aspx file is shown in Example 3.

Example 3. The .aspx file
<%@ Page language="c#" 
Codebehind="WebForm1.aspx.cs" 
AutoEventWireup="false" 
Inherits="WebApplication1.WebForm1" %>

<html>
  <head>
      <meta name=vs_targetSchema content="Internet Explorer 5.0">
      <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
      <meta name="CODE_LANGUAGE" Content="C#">
  </head>
  <body>
    <form runat="server" ID="Form1">
        <asp:DataGrid id="dataGrid1" runat="server" />
    </form>
  </body>
</html>

All that is left is to bind the data. This is accomplished in the Page_Load method in the code-behind file. If the page is not being posted back, you call a helper method, BindGrid.

BindGrid creates a new ArrayList named bugs and populates it with a couple of instances of the Bug class. It then sets dataGrid1's DataSource property to the bugs ArrayList object and calls BindGrid. The complete C# code-behind file is shown in Example 4, with the complete VB.NET code shown in Example 5

Example 10-4. The code-behind file in C#
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DataGridBindAllColumnsBugs
{
   public class WebForm1 : System.Web.UI.Page
   {
      // declare the controls on the web page
      protected System.Web.UI.WebControls.DataGrid 
         dataGrid1;
   
      public WebForm1(  )
      {
         Page.Init += 
            new System.EventHandler(Page_Init);
      }

      private void Page_Load(
         object sender, System.EventArgs e)
      {
         // if this is the first time
         // the page is to be displayed
         // bind the data
         if (!IsPostBack) 
         {
            BindGrid(  );
         }
      }

      private void Page_Init(
         object sender, EventArgs e)
      {
         InitializeComponent(  );
      }
      void BindGrid(  ) 
      {
         // create the data source
         // add a couple bug objects
         ArrayList bugs = new ArrayList(  );
         bugs.Add(
            new Bug(
            101,
            "Bad Property Value",
            "Jesse Liberty", 
            "XBugs",
            "0.01",
            "Property values incorrect",
            DateTime.Now,
            "High"
            )      // end new bug
         );        // end add

         bugs.Add(
            new Bug(
            102,
            "Doesn't load properly",
            "Dan Hurwitz", 
            "XBugs",
            "0.01",
            "The system fails with error x2397",
            DateTime.Now,
            "Medium"
            )      // end new bug
         );        // end add

         // assign the data source
         dataGrid1.DataSource=bugs;

         // bind the grid
         dataGrid1.DataBind(  );

      }
      #region Web Form Designer generated code
      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent(  )
      {    
         this.Load += 
            new System.EventHandler(this.Page_Load);

      }
      #endregion
   }

   // the Bug class 
   public class Bug
   {
      // private instance variables
      private int bugID;
      private string title;
      private string reporter;
      private string product;
      private string version;
      private string description;
      private DateTime dateCreated;
      private string severity;
      
      // constructor
      public Bug(int id, 
         string title,        // for display
         string reporter,     // who filed bug
         string product, 
         string version, 
         string description,  // bug report
         DateTime dateCreated, 
         string severity)
      {
         bugID = id;                      
         this.title = title;              
         this.reporter = reporter;        
         this.product = product;          
         this.version = version;
         this.description = description;
         this.dateCreated = dateCreated;
         this.severity = severity;
      }

      // public read only properties
      public int        BugID          
                  { get { return bugID; }}
      public string     Title          
                  { get { return title; }}
      public string     Reporter       
                  { get { return reporter; }}
      public string     Product        
                  { get { return product;  }}
      public string     Version        
                  { get { return version;  }}
      public string     Description    
                  { get { return description; }}
      public DateTime   DateCreated    
                  { get { return dateCreated; }}
      public string     Severity       
                  { get { return severity; }}

   }
}
Example 10-5. The complete code-behind file in VB.NET
Public Class WebForm1
    Inherits System.Web.UI.Page
   Protected WithEvents dataGrid1 As System.Web.UI.WebControls.DataGrid

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough(  )> Private Sub InitializeComponent(  )

   End Sub

   Private Sub Page_Init(ByVal sender As System.Object)
      'CODEGEN: This method call is required by the Web Form Designer
      'Do not modify it using the code editor.
      InitializeComponent(  )
   End Sub

#End Region

   Private Sub Page_Load(ByVal sender As System.Object, _
                         ByVal e As System.EventArgs) Handles MyBase.Load

      If Not IsPostBack Then
         BindGrid(  )
      End If
   End Sub

   Private Sub BindGrid(  )
      Dim bugs As New ArrayList(  )
      bugs.Add(New Bug(101, _
         "BadProperty Value", _
         "Jesse Liberty", _
         "XBugs", _
         "0.01", _
         "Property values incorrect", _
         DateTime.Now, _
         "High") _
      )
      bugs.Add( _
         New Bug( _
         102, _
         "Doesn't load properly", _
         "Dan Hurwitz", _
         "XBugs", _
         "0.01", _
         "The system fails with error x2397", _
         DateTime.Now, _
         "Medium") _
      )

      dataGrid1.DataSource = bugs
      dataGrid1.DataBind(  )

   End Sub

End Class

Public Class Bug
   Private _bugID As Int32
   Private _title As String
   Private _reporter As String
   Private _product As String
   Private _version As String
   Private _description As String
   Private _dateCreated As DateTime
   Private _severity As String

   Sub New(ByVal theID As Int32, _
   ByVal theTitle As String, _
   ByVal theReporter As String, _
   ByVal theProduct As String, _
   ByVal theVersion As String, _
   ByVal theDescription As String, _
   ByVal theDateCreated As DateTime, _
   ByVal theSeverity As String)

      _bugID = theID
      _title = theTitle
      _reporter = theReporter
      _product = theProduct
      _version = theVersion
      _description = theDescription
      _dateCreated = theDateCreated
      _severity = theSeverity
   End Sub

   Public ReadOnly Property BugID(  ) As Int32
      Get
         BugID = _bugID
      End Get
   End Property

   Public ReadOnly Property Title(  ) As String
      Get
         Title = _title
      End Get
   End Property

   Public ReadOnly Property Reporter(  ) As String
      Get
         Reporter = _reporter
      End Get
   End Property

   Public ReadOnly Property Product(  ) As String
      Get
         Product = _product
      End Get
   End Property

   Public ReadOnly Property Version(  ) As String
      Get
         Version = _version
      End Get
   End Property

   Public ReadOnly Property Description(  ) As String
      Get
         Description = _description
      End Get
   End Property

   Public ReadOnly Property DateCreated(  ) As String
      Get
         DateCreated = _dateCreated
      End Get
   End Property

   Public ReadOnly Property Severity(  ) As String
      Get
         Severity = _severity
      End Get
   End Property

End Class

When the page is loaded, Page_Load is called, which in turn calls BindGrid. In BindGrid, the bugs ArrayList object is created, and two instances of Bug are added, each representing a bug. The DataSource property of DataGrid1 is set, and DataBind is called. The data grid binds each of the properties in Bug to a column in the data grid.

This result is both spectacular and unacceptable. It is spectacular because you've done so little work to display this data from your data source. You did nothing more than bind the collection to the data grid, and ASP.NET took care of the rest. It is unacceptable because this is not how you want the grid to look: the columns are in the wrong order, there is data you don't want to display, there is no link to a detail record, and so forth.

The data grid will pick up the title for each column from the Bug object. The default column header is the name of the property.


Asp Home | All Asp Tutorials | Latest Asp Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Dan Hurwitz and Jesse Liberty
DataGrid Control in ASP.net
Directives in ASP.net
Lifecycle of a web form in ASP.net
ASP Versus ASP.NET Events
What is Code-Behind in ASP.net
IsPostBack in ASP.net

More Tutorials in Asp
IsPostBack in ASP.net
What is Code-Behind in ASP.net
ASP Versus ASP.NET Events
Lifecycle of a web form in ASP.net
Directives in ASP.net
DataGrid Control in ASP.net
Advantages of Stored Procedures
Event Driven Programming in ASP.net
Advantages of ASP.NET
What is ASP.NET?
Visual Basic .NET Vs Visual C# - (Differences)
IIS and WAP. Configuring IIS to deliver WML (WAP content)
Getting started with ASP
ActiveX component can't create object: 'CDONTS.NewMail' - ASP

More Latest News
Most Viewed Articles (in Asp )
IsPostBack in ASP.net
ActiveX component can't create object: 'CDONTS.NewMail' - ASP
Getting started with ASP
What is ASP.NET?
What is Code-Behind in ASP.net
Directives in ASP.net
DataGrid Control in ASP.net
IIS and WAP. Configuring IIS to deliver WML (WAP content)
Advantages of ASP.NET
Visual Basic .NET Vs Visual C# - (Differences)
Event Driven Programming in ASP.net
Advantages of Stored Procedures
ASP Versus ASP.NET Events
Lifecycle of a web form in ASP.net
Most Emailed Articles (in Asp)
IIS and WAP. Configuring IIS to deliver WML (WAP content)
Lifecycle of a web form in ASP.net
DataGrid Control in ASP.net
Visual Basic .NET Vs Visual C# - (Differences)
What is ASP.NET?
IsPostBack in ASP.net
Event Driven Programming in ASP.net
ASP Versus ASP.NET Events
Directives in ASP.net
Advantages of Stored Procedures
What is Code-Behind in ASP.net
ActiveX component can't create object: 'CDONTS.NewMail' - ASP
Advantages of ASP.NET
Getting started with ASP