Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Ajax DataGrid Sample

3.75/5 (5 votes)
7 Dec 2007CPOL4 min read 1   1.1K  
An article on how to implement DataGrid
Screenshot - AjaxDataGridCode

Introduction

This article describes how to update the data in the ASP.NET 2.0 DataView control through AJAX. Let's consider that there is some e-commerce application that allows customers to buy some products on the Internet. Each time a sale is done, the remaining product quantity is updated. Let's also consider that it is necessary to monitor those quantities in real time (this can be required in case of high volume sales and the necessity of frequently ordering the required products). In such a case, it will be useful to have a webpage with the required products and units in stock data that will be updated through asynchronous calls on a required time interval (let's say 5 sec).

When I had a request to develop a similar page, I spent many hours on the Internet trying to find any working sample that could give me an idea of how to code this. I didn't succeed. Most of the articles had some beautiful words, but didn't have any lines of code. Other articles had samples, but they didn't work. So, after some amount of time, I came up with an approach on how to make this work. I hope this article will help other people who are trying to understand AJAX.

Background

The sample is using data from the Products table in the Northwind database. The approach is based on using the XmlHttpRequest object, by which you can send/get any data from/to server using JavaScript. To implement the AJAX call, you actually need to have two web pages: the one that is visible to the end user and the second one that actually generates the required content for the first webpage. The first page calls the second one through XmpHttpRequest implemented in JavaScript.

Using the Code

In the the sample below, we will have 2 web pages:

  • Default.aspx is the page that will be shown to the end user.
  • DataGrid.aspx will provide the content to the Default.aspx page that will be updated each 5 seconds.

As was mentioned, the sample is using the Northwind database, the connection string to which is provided in the web.config file:

C#
<appSettings>
<add key="DSN" value="server=localhost;Integrated Security=SSPI;database=Northwind" />
</appSettings>

The Business Logic Layer is located in the App_Code\BLL subfolder and contains the ProductsBLL.cs class. It has one method, GetProducts(), that actually returns all products for CategoryId=1 from the Products table in the Northwind database.

C#
/// 
<summary />/// Summary description for ProductsBLL 
/// </summary />public class ProductsBLL 
{
    public static void GetProducts(DataSet ds) 
    { 
        string sqlString = 
            "SELECT ProductId, ProductName, QuantityPerUnit UnitPrice, " + 
            "UnitsInStock FROM Products WHERE CategoryId=1 order by ProductName"; 
        SqlHelper.FillDataset(SqlHelper.connection(), 
            CommandType.Text, sqlString, ds, new string[] { "Products" }); 
    } 
}

The above method is using the FillDataset method from the Data Access Layer, which is located in the App_Code\DAL subfolder. It contains one class, SqlHelper.cs, that contains a collection of data access methods. The SqlHelper.cs class was created based on open source application block data access classes and can be successfully used to access data in SQL an database. Let's now consider the DataGrid.aspx webpage. This page contains the Label1 control and the gvGrid GridView control, both of which are populated via the Page_Load event. The DataView control is populated with data from Products data set. Label1.Text is updated with the current date/time.

C#
protected void Page_Load(object sender, EventArgs e) 
{ 
    DataSet ds = new DataSet(); 
        ProductsBLL.GetProducts(ds); 
    gvGrid.DataSource = ds; 
    gvGrid.DataBind(); 


    
    Label1.Text = "Units in Stock for: " + DateTime.Now.ToString(); 
}

The Default.aspx page contains a <div> section with id="GridSection" and Input button btnGet that calls the Ajax JavaScript function doCall() on onclickevent. The data that will be received through AJAX calls will be placed inside the above <div> element.

<input id="btnGet" type="button" value="Get Data" onclick="doCall()"/> 
.
.
.
<div id= "GridSection">

</div>

Now let's consider the Ajax.js JavaScript that actually does the whole job.

C#
// Creating the instance of the XmlHttpRequest 
// This is done differently for different browsers
// Branch for native XMLHttpRequest object 
var client=null; 
if (window.XMLHttpRequest) 
{ 
    client = new XMLHttpRequest(); 
} 

// Branch for IE/Windows ActiveX version 
else if (window.ActiveXObject) 
{ 
    client = new ActiveXObject("Microsoft.XMLHTTP"); 
} 

//Sending information to server 
function doCall() 
{ 
    try 
    { 
        //callBack; 
        var url="DataGrid.aspx" 
        url=url+'?d='+Date(); 
        client.open("GET", url); 
        client.onreadystatechange = callBack; 
        client.send(); 
    } 
    catch(ex) 
    { 
        alert(ex.message); 
    } 
 
    setTimeout('doCall()', 5000); //5 sec 
} 
 
//Waiting and processing server response 
function callBack(response) 
{ 
    try 
    { 
        if(client.readyState == 4 && client.status == 200) 
        { 
            xmlDocument = new ActiveXObject('Microsoft.XMLDOM'); 
            xmlDocument.async = false; 
 
            //The responseText is loaded into XML document 
            xmlDocument.loadXML(client.responseText); 
 
 
         //Get the 
        node vargridNode=xmlDocument.selectSingleNode('/html/body/form/div[@id="Grid"]');
 
            //Replace innerHTML of the default.aspx page with the response node.xml 
            document.getElementById("GridSection").innerHTML=gridNode.xml; 
        } 
    } 
    catch(ex) 
    { 
    alert(ex.message); 
    } 
}

To test the sample, open Default.aspx page and click the "Get Data" button. The page will be populated with DataView, with products data from Products table in the Northwind database. The data in DataView are refreshed every 5 seconds. To test this functionality, open the Northwind database's Products table and exchange the UnitsInStock field data for some product from CategoryId=1. The data on the Default.aspx web page will be changed within 5 seconds without being posted back.

Points of Interest

Using the above technique, it is possible to update various parts of the page with different data asynchronously. This can be useful when working with the data that should be refreshed to the user not only when the user posts back the page, but rather at some certain time intervals.

History

  • 3 December, 2007 -- Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)