JG Vimalan's Blog

Sharing is caring :)

Dynamic columns in jqGrid

In this post we are going to see how to display jqGrid with dynamic columns.
I am using the following plugins and languages for preparing this article,
a. jqGrid 4.5.4 plugin
b. jQuery 1.8.2
c. ASP.NET WebForms
d. C#
e. Visual Studio 2012

Step 1:

I am assuming that you already have an ASP.NET project configured with jqGrid plugin.
The first thing to do is, create a class as shown below to hold the column header names, model names and actual data generated at runtime.

public class Dashboard
{
private List _model = new List();
//at runtime you will know the column names, set them here.
public List Model
{
get
{
return _model;
}
set
{
_model = value;
}
}

private List _headers = new List();
//if you want to give more meaningful names for column, set them here.
//The order of model name should match with header name
public List Headers
{
get
{
return _headers;
}
set
{
_headers = value;
}
}
//Store the actual data generated at runtime here.
//I converted datatable generated at runtime in to List<Dictionary<string, object>>
public List<Dictionary<string, object>> DashboardContent { get; set; }

}

Step 2:

In your ASP.NET page, define table controls as shown below,

<table id=”ReportGrid”></table>
<div id=”ReportGridPager”></div>

Step 3:

In the code behind, write the WebMethod that returns the Dashboard object.

[WebMethod]
public static Dashboard GetReportDashboard()
{
//In the ‘GetDailyDashboard’ method, you will get dynamic data from database
//and build the datatable at runtime. Then get the columns, headers from datatable and set it to
//Model and Headers property in Dashboard object. Also convert the datatable to
//List<Dictionary<string, object>> object and set it to DashboardContent property.

return ReportQueryManager.GetDailyDashboard();
}

Step 4:

In your javascript file, which holds the logic to build jqGrid on table object use the following code,

Basically, in the AJAX success method, get the Dashboard property values and set them to
jqGrid properties and bind the data to jqGrid.

$.ajax({
url: methodUrl, //set the method url here
dataType: “json”,
type: ‘POST’,
data: null,
contentType: “application/json; charset=utf-8”,
success: function (data) {
var dataArray = data.d //here you get the Dashboard object

var reportModel = dataArray.Model //Model property in Dashboard object
var header = dataArray.Headers ////Header property in Dashboard object
var dashboardData = dataArray.DashboardContent //Actual data with column

var ColModel = [];
for (index in reportModel ) {
var colName = reportModel[index]
var colWidth = 100
var isFixed = false
var sortTypeValue = “int”
var alignPosition = ‘center’

if (colName == “Name”) {
isFixed = true
colWidth = 300
sortTypeValue = “text”
alignPosition = ‘left’
}
ColModel.push({ name: colName, index: name, frozen: isFixed, width: colWidth, sorttype: sortTypeValue,
align: alignPosition });
}

var customButton = function (options) {
ReportGrid.jqGrid(‘navButtonAdd’, pageSelector, options);
ReportGrid.jqGrid(‘navButtonAdd’, ‘#ReportGrid’ + “_toppager”, options);
};

ReportGrid.jqGrid({
datatype: “local”,
mtype: “GET”,
cmTemplate: { sortable: true, resizable: true },
height: $(document).height() – reduceGridHeight,
rowNum: 20,
rowList: [],
altRows: true,
altclass: ‘gridAltRowClass’,
gridview: true,
pgbuttons: false,
loadonce: true,
shrinkToFit: false,
autoencode: true,
sortname: null,
width: $(“#SerReportGridWrapper”).width(),
ignoreCase: true,
viewrecords: true,
sortorder: “desc”,
pager: pageSelector,
pgtext: null,
scrollrows: true,
loadui: ‘disable’,
colNames: header, //set the header object here
colModel: SerColModel, //set the model object here
caption: “Dashboard”
});

ReportGrid.jqGrid(‘navGrid’, ‘#ReportGridPager’, {
view: true, add: false, edit: false, del: false, refresh: false, search: false, viewtext: ‘View Selected Row’
}, {}, {}, {}, {},
{ width: 400 });

ReportGrid.jqGrid(‘setFrozenColumns’);

customButton({
caption: “Export To Excel”,
title: “Export To Excel”,
onClickButton: function () {
if (serReportGrid.jqGrid(‘getGridParam’, ‘records’) == 0) {
Block(ReportGridBox, “No record(s) found to export”)
}
else {
Export()
}
}
});

ReportGrid[0].addJSONData(dashboardData);
},
error: function (d) {
if (d.statusText != ‘abort’) {
$.unblockUI();
$(“#ErrorMessage”).show()
}
}
});

Thats all. Now, you will be able to display dynamic columns in your jqGrid.

February 23, 2014 Posted by | ASP.NET, C#.NET, JavaScript, jqGrid, JQuery, JSON | , | 3 Comments