Friday, October 06, 2006

Generate Grid using Script callback (Ajax for 2003)

Hi All,

I am back after long time. I have a requirement to display a grid using sript call back. I search on net and found that all solutions suggest that generate XML file and pass it to java script. Itrate through XML file and generate "" for each row. I found this solution bit complex and require good knowledge of javascript and XML. I was looking for some easy slotion. For the same project I was writing the code for Export to excel. The same "common" code that we found on net. :) I found that this can help me in my grid problem as GridView.RenderControl(object of HTMLWriter); generates HTML for grid. What I did is I took that generated HTML in to string and passed it to javascript. In javascript I assigned that to innerHTML of DIV. See the code below..

Javascript Code

<script language="javascript" type="text/javascript">

function GenerateGrid(object)
var message = document.getElementById("ddlEmployeeName").value ;
var context = '';
<%= strCallback %>
return false;

function GenerateGridData(message,context)
// Here lblGrid is name of my lable.
document.getElementById("lblGrid").innerHTML = message;


Server Side Code

Here I have removed extra code.

public void RaiseCallbackEvent(string eventArgument)
// Create new GridView and Bind it
GridView gvGridView = new GridView ();
gvGridView.DataSource = ds;

// Get string writer and HTML writer
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);

// This will generate HTML

strData = sw .ToString();


public string GetCallbackResult()
// return value to javascript
return strData;

How simple!!! I have displayed the grid without XML file and iteration logic of javascript. Then I remember a good quote of my friend, the rule of "KIS (Keep It Simple)". I am working on paging and editing of grid with script callback and will soon post the blog.

Bye and do happy programming.