Programming Tutorials

DataGrid Control in ASP.net

By: Dan Hurwitz and Jesse Liberty in Asp.net Tutorials on 2009-02-27  

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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Asp.net )

Severity Code Description Project File Line Suppression State Error CS0103 The name 'Encoding' does not exist in the current context

Getting values from appsettings.json ASP.NET

HttpError is not found in Asp,net core project

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'JToken' could not be found.

Severity Code Description Project File Line Suppression State Error CS0103 The name 'JsonConvert' does not exist in the current context.

IIS and WAP. Configuring IIS to deliver WML (WAP content)

Development Mode in IIS for Asp.net projects

Severity Code Description Project File Line Suppression State Error CS0308 The non-generic type 'List' cannot be used with type arguments.

Downloading and Installing the AWS SDK for .NET

Things to note when changing a function to async in your controller

One client credential type required either: ClientSecret, Certificate, ClientAssertion or AppTokenProvider must be defined when creating a Confidential Client. Only specify one

Visual Basic .NET Vs Visual C# - (Differences)

Severity Code Description Project File Line Suppression State Error CS1061 'string[]' does not contain a definition for 'Any' and no accessible extension method 'Any' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)

Pass the same model to multiple views within the same controller

Button that is only clickable when the checkbox is checked

Latest Articles (in Asp.net)

Things to note when changing a function to async in your controller

AmbiguousMatchException: The request matched multiple endpoints.

Call an Action in a controller when user clicks a button in View

Button that is only clickable when the checkbox is checked

Pass the same model to multiple views within the same controller

Severity Code Description Project File Line Suppression State Error CS0103 The name 'Encoding' does not exist in the current context

Severity Code Description Project File Line Suppression State Error CS0103 The name 'JsonConvert' does not exist in the current context.

Passing a model globally to all Views in your Asp.net webapp

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'JToken' could not be found.

Severity Code Description Project File Line Suppression State Error CS0308 The non-generic type 'List' cannot be used with type arguments.

One client credential type required either: ClientSecret, Certificate, ClientAssertion or AppTokenProvider must be defined when creating a Confidential Client. Only specify one

Severity Code Description Project File Line Suppression State Warning Found conflicts between different versions of the same dependent assembly.

Severity Code Description Project File Line Suppression State Error CS1061 'string[]' does not contain a definition for 'Any' and no accessible extension method 'Any' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)

Pagination in ASP.net core application

Microsoft.Identity vs Microsoft.IdentityModel.Clients.ActiveDirectory

Related Tutorials

Things to note when changing a function to async in your controller

AmbiguousMatchException: The request matched multiple endpoints.

Call an Action in a controller when user clicks a button in View

Button that is only clickable when the checkbox is checked

Pass the same model to multiple views within the same controller

Severity Code Description Project File Line Suppression State Error CS0103 The name 'Encoding' does not exist in the current context

Severity Code Description Project File Line Suppression State Error CS0103 The name 'JsonConvert' does not exist in the current context.

Passing a model globally to all Views in your Asp.net webapp

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'JToken' could not be found.

Severity Code Description Project File Line Suppression State Error CS0308 The non-generic type 'List' cannot be used with type arguments.

One client credential type required either: ClientSecret, Certificate, ClientAssertion or AppTokenProvider must be defined when creating a Confidential Client. Only specify one

Severity Code Description Project File Line Suppression State Warning Found conflicts between different versions of the same dependent assembly.

Severity Code Description Project File Line Suppression State Error CS1061 'string[]' does not contain a definition for 'Any' and no accessible extension method 'Any' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)

Pagination in ASP.net core application

Microsoft.Identity vs Microsoft.IdentityModel.Clients.ActiveDirectory