JG Vimalan's Blog

It is all about coding!

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.

Advertisements

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

Microsoft JScript runtime error: ‘JSON’ is undefined

I received this error when I tried to run my ASP.NET webpage in IE 8 Compatibility mode. JSON.parse function seems to be not working in IE 8 Compatibility mode.  The snapshot is given below,

json_error

In order to fix this issue, add reference to json2.min.js file in your ASP.NET webpage.  This file can be downloaded from NuGet, http://nuget.org/packages/json2/ . This will solve the issue.

April 9, 2013 Posted by | ASP.NET, JQuery, JSON | , , | Leave a comment

Enable / Disable ASP.NET TextBox control using jquery

The following code snippet will give you an idea for enabling or disabling an asp.net control using jquery,

Here, based on the option (true or false), I am enabling / disabling a textbox, setting its background color to lightgrey and clearing the text.

<head runat=”server”>
<script src=”Scripts/jquery-1.8.2.min.js” type=”text/javascript”></script>
<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {
var optionChkBox = $(“#chkOption”)
optionChkBox.change(function () {
var status = optionChkBox.is(‘:checked’)

var nameTxtBox = $(“#txtBoxName”)
if (status) {
nameTxtBox.attr(‘disabled’, false)
nameTxtBox.css(“background-color”, “white”)
}
else {
nameTxtBox.val(”)
nameTxtBox.attr(‘disabled’, true)
nameTxtBox.css(“background-color”, “lightgray”)
}
})
});
</script>

October 16, 2012 Posted by | ASP.NET, JQuery, VS 2010 | Leave a comment

This OdbcTransaction has completed; it is no longer usable.

I got this exception when I was trying to perform multiple row insert in a DB2 database using Enterprise Library 5.0 and DbTransaction.

Cause of this exception:

I was trying to invoke ExecuteNonQuery method from Database object instead of DbCommand object. And, when one of the SQL failed (due to syntax or data problem), the catch block caught the exception and tried to rollback but DbTransaction.Rollback failed and it was throwing the above exception.

Solution:

In order to solve this issue, set the transaction object in DBCommand.Transaction property and ExecuteNonQuery in DbCommand. Plus, the connection should be in open state when trying to rollback. The working code sample is given below,

internal static bool InsertRecords(List<string> sqlCollection)
{
Database database = DatabaseFactory.CreateDatabase(Utility.GetDB2ConnectionName);

using (DbConnection dbConnection = database.CreateConnection())
{
DbCommand dbCommand = dbConnection.CreateCommand();
DbTransaction dbTransaction = null;

try
{
dbConnection.Open();
dbTransaction = dbConnection.BeginTransaction();
dbCommand.Transaction = dbTransaction;

foreach (string sql in sqlCollection)
{
dbCommand.CommandText = sql;
dbCommand.CommandType = CommandType.Text;
dbCommand.ExecuteNonQuery();
}

dbTransaction.Commit();
return true;
}
catch (Exception error)
{
Log.Error(error);

if (dbTransaction != null)
dbTransaction.Rollback();
}
}

return false;
}

October 2, 2012 Posted by | ASP.NET, C#.NET, DB2, Enterprise Library 5.0, VS 2010 | | Leave a comment

Save xml file in client machine without user interaction using asp.net

I got a task where I need to save an xml file in client machine whenever user vists a specific asp.net webpage. As my web application is IE compatible only, I have not verified this solution in other browsers.

In the following code I am going to read an xml file (data source) from the server and paste it in the client machine. The data source can be a session object, a variable in the code behind or a value in hidden field in asp.net page. My sample project structure is given below,

As a first step, add reference to jquery in your aspx page. Using jquery ajax, read the xml file. Then, using FileSystemObject ActiveX create the file in the target location. Then populate the file with the xml object.

Complete code is given below,

<head runat=”server”>
<title>Process XML using jQuery</title>
<script src=”Scripts/jquery-1.7.2.min.js” type=”text/javascript”></script>

<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {;
$.ajax({
type: “GET”,
url: “UserInfo.xml”,
dataType: “xml”,
success: function (xmlObj) {
var fileSystemObject = new ActiveXObject(“Scripting.FileSystemObject”);
varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0);
varFileObject.write(xmlObj.xml);
varFileObject.close();
alert(“Download complete”);
close();
},
error: function () {
alert(“Download failed. Please contact the administrator.”);
}
});
});

</script>

This does not require any user interaction. I am displaying javascript alert messages just for testing purpose.

In the line, varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0); parameter true creates the file if it does not exist.

September 21, 2012 Posted by | ASP.NET, JavaScript, JQuery, VS 2010 | 6 Comments

Clickable GridView with Postback in ASP.NET 4.0

In this post, I will show you how to make a GridView row clickable and read the selected row values after postback.

Step 1:

Create an ASP.NET 4.0 web application. Add a gridview control in the application.

Step 2:

Create RowCreated and RowDataBound events and set their values as shown below,

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add(“onclick”, “CreatePostBack(this);”);
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add(“onmouseover”, “mouseIn(this);”);
e.Row.Attributes.Add(“onmouseout”, “mouseOut();”);
}
}

Here, the CreatePostBack(this); is a javascript function. In this function call the _doPostBack function and pass the necessary parameters as shown below,

<script type=”text/javascript”>
function mouseIn(row) {
document.body.style.cursor = ‘pointer’;
}
function mouseOut() {
document.body.style.cursor = ‘auto’;
}

function __doPostBack(eventTarget, eventArgument) {
var theForm = document.forms[‘ctl01’];
if (!theForm) {
theForm = document.ctl01;
}
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

function CreatePostBack(row) {

__doPostBack(‘GridView1’, row.rowIndex);

//in this example, i am just passing the rowIndex. You can read the selected row values and pass them.
}
</script>

Step 3:

Add two hidden fields as shown below for capturing the  event target and event argument,

<input type=”hidden” name=”__EVENTTARGET” id=”__EVENTTARGET” value=”” />
<input type=”hidden” name=”__EVENTARGUMENT” id=”__EVENTARGUMENT” value=”” />

Step 4:

In the Page Load event, set the data source for the gridview control and the code for reading the values when there is a post back,

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetUsers(); //use your method for getting datasource value here
GridView1.DataBind();
}
else if (Request.Form[“__EVENTTARGET”] == “GridView1”)
{
var arg = Request.Form[“__EVENTARGUMENT”];
//now you got the selected row values
}
}

Step 5:

Thats all! The Gridview markup is given below for your reference,

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<input type=”hidden” name=”__EVENTTARGET” id=”__EVENTTARGET” value=”” />
<input type=”hidden” name=”__EVENTARGUMENT” id=”__EVENTARGUMENT” value=”” />
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”false”
onrowcreated=”GridView1_RowCreated” onrowdatabound=”GridView1_RowDataBound”>
<Columns>

….

</Columns>
</asp:GridView>
</asp:Content>

So, whenever a gridview row is clicked, the postback will happen and you can read the selected row values.

The working sample can be downloaded from here,

https://docs.google.com/file/d/0By3at1G2EGgOYTNYQ1ZuQi11aXc/edit

File->Download

September 15, 2012 Posted by | ASP.NET, C#.NET, VS 2010 | , | 9 Comments