Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET
Article

Ajax DataGrid Sample

Rate me:
Please Sign up or sign in to vote.
3.75/5 (5 votes)
7 Dec 2007CPOL4 min read 91K   1.1K   34   13
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)


Written By
Web Developer
Canada Canada
Born in Russia, St.Petersburg. Graduated St.Petersburg State University as astrophysics.
Live in Canada, Toronto since 1997.
Worked as Software Developer, Solutions Architect, Database Designer and Administrator, Software Development Manager. During last 4 years was working as Sr. NET Consultant in various financial institutions and companies.
Have the following Microsoft certificates: MCP, MCSD, MCDBA.

Comments and Discussions

 
Generalthanks dude Pin
cempreng29-Jun-10 15:00
cempreng29-Jun-10 15:00 
GeneralNot execution - solution Pin
Bo Vistisen2-Jan-10 0:40
Bo Vistisen2-Jan-10 0:40 
Generalget error msg Pin
mikedgre18-Dec-08 12:12
mikedgre18-Dec-08 12:12 
QuestionNot Worked in FireFox and Safary?? Pin
chirprit9-Jul-08 3:49
chirprit9-Jul-08 3:49 
Generalhelp Pin
Thunderbird7779-Apr-08 2:07
Thunderbird7779-Apr-08 2:07 
GeneralGood article overall Pin
nsimeonov12-Dec-07 16:49
nsimeonov12-Dec-07 16:49 
I liked the article but (again) I have a few ideas how to make it better First you better return only the changed rows instead of the entire grid. Yes it would require a bit more parsing clientside but also it would minimize the traffic - I'm assuming that only a few items may change not everything. This would require to set IDs for each UnitInStock cell or put a
or in it, but refreshing every couple of seconds - this would save lots of bandwidth. Also instead of XML I would use a simple format like comma-separated values (ID1,value1)\n(ID2,value2)\n so I could just split(\n) to get each ID/value pair then for each of them I'd split(',') it to get the values and update the HTML.

Note: I'm talking about a very specific solution for the problem you described. In general your approach is good, except I don't see the point in parsing the html like you do: you better return the grid as plain text and then replace the html like this: document.getElementById("GridSection").innerHTML=client.responseText;


I know it's a personal preference but I'd also combine doCall and callBack and I would put callBack as inline function do I don't have to define global variables. If it's part of a framework it would help you do parallel requests like updating 2 separate grids at the same time.

And in the end - I'd put the setTimeout(...) in the callBack function after all the processing is done, not in doCall so if we're on a slower network the requests wouldn't overlap and eat the entire bandwidth.

About the compatibility - I see you are checking for windows.XmlHttpRequest when creating the object but in callBack you are creating an ActiveXObject that's not likely to work on non-IE browsers, can't you use client.response.XML instead?


-----------------

Edit: I'm proposing a more efficient way for doing this because that would be the only reason not to use any of the available ajax frameworks, saving you the compatibility problems you may stumble upon when you try to write cross-browser javascript functions.
GeneralRe: Good article overall Pin
Ekaterina Kostrioukova13-Dec-07 3:30
Ekaterina Kostrioukova13-Dec-07 3:30 
Generalnot executing Pin
Farrru7-Dec-07 23:29
Farrru7-Dec-07 23:29 
GeneralRe: not executing Pin
Ekaterina Kostrioukova10-Dec-07 3:42
Ekaterina Kostrioukova10-Dec-07 3:42 
GeneralRe: not executing Pin
liumin10-Dec-07 22:11
liumin10-Dec-07 22:11 
GeneralRe: not executing Pin
Ekaterina Kostrioukova12-Dec-07 3:48
Ekaterina Kostrioukova12-Dec-07 3:48 
GeneralRe: not executing Pin
nsimeonov12-Dec-07 16:48
nsimeonov12-Dec-07 16:48 
GeneralRe: not executing Pin
robdeyric19-Nov-09 19:55
robdeyric19-Nov-09 19:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.