Click here to Skip to main content
15,180,782 members
Articles / Web Development / ASP.NET
Article
Posted 6 Dec 2007

Stats

87.4K views
1.1K downloads
34 bookmarked

Ajax DataGrid Sample

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

Share

About the Author

Ekaterina Kostrioukova
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 16:00
Membercempreng29-Jun-10 16:00 
GeneralNot execution - solution Pin
Bo Vistisen2-Jan-10 1:40
MemberBo Vistisen2-Jan-10 1:40 
For more than two years this nice sample have suffered from a tiny fault - the code will not execute.
"Object required." is all you get when you run the code. It is not a IE6 or IE7 error.
It is a very simple error.

In the java code it is the "var gridNode=xmlDocument.selectSingleNode('/html/body/form/div[@id="Grid"]');" that fails.
It fails because the "xmlDocument.loadXML(client.responseText);" in the previous line never loaded due to a parser error.

The error is caused because of the line:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

in the "DataGrid.aspx" file. It refers some DTD? that Katerina might have installed since she did not get the error.

Solution: Just delete that line! (You can delete it in Default.aspx too if you like)

Let me address another problem I often run into when testing these samples.

It is linking up to the datafile.
The Northwind database is often used as an example and for a good reason. Many has it installed or have the file.
Personally I like to have the "NORTHWIND.MDF" file in the App_Data folder and the alter the connection string in the Web.Config file to
<!-- <add key="DSN" value="server=localhost;Integrated Security=SSPI;database=Northwind"/> -->
<add key="DSN" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWIND.MDF;Integrated Security=True;User Instance=True;"/>

If you don't have the NORTHWIND.MDF (SQL file) or the Northwind.mdb (Access file) here is how to get it.

First let me remind you of a local Codeproject article HowTo: Install the Northwind and Pubs Sample Databases.

If you are a C# programmer download the CsharpSamples.zip here. You will find it under "\LinqSamples\Data". And of cause there are the samples too.

If you are a VB programmer you will have to start at the MSDN page for downloading the "VS 2008 RTM VBSamples.zip" file. That file too holde a lot of good samples and NORTHWIND.MDF in the "VB RTM Samples\Language Samples\LINQ Samples\LinqToNorthwind\LinqToNorthwind\Data" folder.

Should you, like me, still often like to program your web applications up to a MS Access file you can get Nwind.mdb by downloading it here at Microsoft. This makes you independant of any SQL Server running and MS Access let you easily make queries and reports that you still not have programmed for.

Before we enter 2010 with the new VS2010 comming up let me reference two nice links for VS2008.

Most of us have until now used this product to develop our applications with so it might have some interest. Many right now is using .NET Framework 3.5 though .NET Framework 4.0 is available.

It's more or less two years since VS2008 was introduced with a lot of new features.
Visual Studio 2008 - New Features can be found here at CodeProject.

Later Scott Guthrie wrote Visual Studio 2008 and .NET Framework 3.5 Service Pack 1 Beta on his blog giving a nice introduction of some of the new features and improvements that is being added by the Service Packs and the .NET Framworks.

Thank you Katrina Kostrioukova for this and her other contributions to this web site.
Bo Vistisen
Generalget error msg Pin
mikedgre18-Dec-08 13:12
Membermikedgre18-Dec-08 13:12 
QuestionNot Worked in FireFox and Safary?? Pin
chirprit9-Jul-08 4:49
Memberchirprit9-Jul-08 4:49 
Generalhelp Pin
Thunderbird7779-Apr-08 3:07
MemberThunderbird7779-Apr-08 3:07 
GeneralGood article overall Pin
nsimeonov12-Dec-07 17:49
Membernsimeonov12-Dec-07 17:49 
GeneralRe: Good article overall Pin
Ekaterina Kostrioukova13-Dec-07 4:30
MemberEkaterina Kostrioukova13-Dec-07 4:30 
Generalnot executing Pin
Farrru8-Dec-07 0:29
MemberFarrru8-Dec-07 0:29 
GeneralRe: not executing Pin
Ekaterina Kostrioukova10-Dec-07 4:42
MemberEkaterina Kostrioukova10-Dec-07 4:42 
GeneralRe: not executing Pin
liumin10-Dec-07 23:11
Memberliumin10-Dec-07 23:11 
GeneralRe: not executing Pin
Ekaterina Kostrioukova12-Dec-07 4:48
MemberEkaterina Kostrioukova12-Dec-07 4:48 
GeneralRe: not executing Pin
nsimeonov12-Dec-07 17:48
Membernsimeonov12-Dec-07 17:48 
GeneralRe: not executing Pin
robdeyric19-Nov-09 20:55
Memberrobdeyric19-Nov-09 20: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.