Related
I want to convert datatable to a format that I can feed in to Google Charts in .Net MVC application.
I retrieve my data from the database and put it in a C# Datatable. Now I want to convert that into a format that google charts can understand. I have included the code for what I have so far. I keep getting error from google charts: "First row is not an array.".:
//Controller
public static string GetData()
{
String sql = "Select * from someTable";
//Run above sql against database and get back a DataTable
DataTable dt = new Utility().ConnectionUtility(sql);
//Convert DataTable to Json Object (I followed this link: https://codepedia.info/convert-datatable-to-json-in-asp-net-c-sharp/)
return JsonConvert.SerializeObject(dt);
}
//View
<div id="barChart" style="width:750px; height: 400px;"></div>
<script>
// Here We will fill chartData
$(document).ready(function () {
$.ajax({
url: "GetData",
dataType: "json",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartData = data;
},
error: function (xhr, status, error) {
alert('Message');
}
}).done(function () {
// after complete loading data
google.setOnLoadCallback(drawChart);
drawChart();
});
});
function drawChart() {
var datapie = google.visualization.arrayToDataTable(chartData);
var options = {
title: "Test Execution",
width: 600,
height: 400,
bar: { groupWidth: "75%" },
};
var Chartpie = new google.visualization.BarChart(document.getElementById('barChart'));
Chartpie.draw(datapie, options);
}
</script>
Maybe it's a little late, but today i have encountered the same situation.
In your controller side, you need to shape your data according to chart type.
Then in your view side, just use google.visualization.arrayToDataTable(Your Data);
here is a sample code...
[HttpPost]
public JsonResult AjaxMethod()
{
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"HEADER1", "HEADER_NUMERIC_AREA"
});
//get data table from sql.
DataTable DT = Direkbaglan.DBListele(" SELECT [StockName] ,[Weight] FROM STOCKS ");
for (int i = 0; i < DT.Rows.Count; i++)
{
chartData.Add(new object[]
{
DT.Rows[i][0], DT.Rows[i][1]
});
}
return Json(DT);
}
view side
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Home/jsongonder",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
//Pie
var options = {
title: 'Stock Info (weight)'
};
var chart = new google.visualization.PieChart($("#chart1")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart1" style="width: 500px; height: 400px;">
</div>
</body>
</html>
My image viewer :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="http://cdn.sencha.com/ext/gpl/5.1.0/build/packages/ext-theme-classic/build/resources/ext-theme-classic-all.css">
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/5.1.0/build/ext-all.js"></script>
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/5.1.0/build/packages/ext-theme-classic/build/ext-theme-classic.js"></script>
<style>
.thumbnail {
padding: 4px;
background-color: #e6e6e0;
border: 1px solid #d6d6d0;
float: left;
margin-right: 10px;
margin-bottom: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<script>
Ext.define('Image', {
extend: 'Ext.data.Model',
fields: [
{ name: 'href', type: 'string' },
{ name: 'caption', type: 'string' }
]
});
var imagesStore = Ext.create('Ext.data.Store', {
id: 'imagesStore',
model: 'Image',
data: [
{ href: 'images/Hydrangeas.jpg', caption: 'Hydrangeas' },
{ href: 'images/Jellyfish.jpg', caption: 'Jellyfish' },
{ href: 'images/Koala.jpg', caption: 'Koala' },
{ href: 'images/Lighthouse.jpg', caption: 'Lighthouse' }
]
});
var imageTpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumbnail" onClick="javascript:openWindow(this.lightbox);" >',
'<img src="{href}" width="200px" height="150px" />',
'<br/><span>{caption}</span>',
'</div>',
'</tpl>'
);
var sel_thumb_id = 0;
var thumbs = Ext.create('Ext.view.View', {
id: 'thumbs',
store: Ext.data.StoreManager.lookup('imagesStore'),
tpl: imageTpl,
itemSelector: 'img',
emptyText: 'No images available',
renderTo: document.body,
listeners: {
}
});
var img = Ext.create('Ext.Img', {
id:'img',
src: '',
shrinkWrap: true
});
var next = Ext.create('Ext.Button', {
xtype: 'button',
text: 'Next',
width: 100,
handler: function () {
if (img_id < imagesStore.data.items.length ) {
img_id = img_id + 1;
var nextSrc = imagesStore.data.items[img_id].data.href;
console.log(nextSrc);
Ext.getCmp('img').setSrc(nextSrc);
}
}
});
var previous = Ext.create('Ext.Button', {
xtype: 'button',
text: 'Previous',
width: 100,
handler: function () {
if (img_id > 0) {
img_id = img_id - 1;
var nextSrc = imagesStore.data.items[img_id].data.href;
Ext.getCmp('img').setSrc(nextSrc);
}
}
});
var lightbox = new Ext.window.Window( {
id: 'lightbox',
title: '',
height: 600,
width: 800,
layout: 'fit',
items: [img],
modal: true,
draggable: false,
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
padding: '5 20',
align: 'center',
items: [previous, next]
}],
closeAction: 'hide',
resizable: false
})
function openWindow(lightbox) {
img.setSrc('images/Hydrangeas.jpg');
Ext.getCmp('lightbox').show();
img_id = 0;
}
</script>
</body>
In this way, images are stored in a folder. Now i want to load images from database. I don't mean image path from database, i mean image. I can get images data from database using c# asmx web service.
1) What type should i choose to store images in ms sql ?
2) How can i convert data that i will get from database and display as images ?
I want to load all the events from the database in the calendar as the page loads but it's not working. Thedata is comming to the page from database but the object is not showing events.
My model is
public class Calendar
{
public int id { get; set; }
public string title { get; set; }
public DateTime starttime { get; set; }
public DateTime endtime { get; set; }
}
My controller methods are
[HttpPost]
public JsonResult dataReceiver(string title)
{
Calendar calendar = new Calendar();
calendar.title = title;
calendar.starttime = DateTime.UtcNow.ToLocalTime();
calendar.endtime = DateTime.UtcNow.ToLocalTime().AddDays(5);
db.Calendars.Add(calendar);
db.SaveChanges();
return Json(title, JsonRequestBehavior.AllowGet);
}
public ActionResult datasender()
{
var search = from m in db.Calendars select m;
//ViewBag.Message = search.ToList();
return Json(search.ToList(),JsonRequestBehavior.AllowGet);
}
and my view is
<html>
<head>
<title> Calendar</title>
<link href="~/Content/calendar/fullcalendar.css" rel="stylesheet" />
<link href="~/Content/calendar/fullcalendar.print.css" rel="stylesheet" media='print' />
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<style>
body {
margin: 40px 10px;
padding: 0;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
font-size: 14px;
}
#calendar {
max-width: 900px;
margin: 0 auto;
}
.fc-ltr {
background: #ddba8f;
}
.fc-toolbar {
background: #c64343;
}
</style>
</head>
<body>
<div id='calendar' style="height:90%; width:90%; color:black; border:1px solid blue; margin-top:5%; position:relative">
</div>
</body>
</html>
#section scripts
{
<script src="~/Scripts/calendar/moment.min.js"></script>
<script src="~/Scripts/calendar/jquery.min.js"></script>
<script src="~/Scripts/calendar/fullcalendar.js"></script>
<script src="~/Scripts/calendar/jquery-ui.custom.min.js"></script>
<script>
$(document).ready(function () {
calendarcreate();
var obj;
});
function calendarcreate() {
$.ajax({
type: "Post",
url: "/Calendar/datasender",
dataType: "html",
data: {},
success: function (data) {
obj = JSON.parse(data);
alert("successfull data received " + JSON.stringify(obj));
var cal = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
type: "Post",
url: "/Calendar/dataReceiver",
dataType: "json",
data: { "title": eventData.title },
success: function (data) {
alert("successfull data send " + data);
},
error: function (req, status, error) {
alert(error + req + status);
}
});
},
eventClick: function (calEvent, jsEvent, view) {
alert(calEvent.title + calEvent.start + calEvent.end +obj)
},
dragOpacity: .50,
dragRevertDuration: 1000,
eventColor: '#378006',
eventBackgroundColor: 'gray',
editable: true,
eventStartEditable: true,
eventDurationEditable: true,
dragScroll: true,
eventOverlap: false,
eventLimit: true, // allow "more" link when too many events
events:
[
{
title: 'All Day Event',
start: '2015-02-01'
},
{
id: 999,
title: 'Repeating Event',
start: '2015-02-09T16:00:00'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2015-02-28'
}
]
});
},
error: function (req, status, error) {
alert(error + req + status);
var div = $('#SearchItemDiv');
div.html("");
div.append('Error');
}
});
}
</script>
function calendarcreate() {
$.ajax({
type: "Post",
url: "/Calendar/datasender",
dataType: "html",
data: {},
success: function (data) {
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});
obj = JSON.parse(data);
alert("successfull data received " + JSON.stringify(obj));
var cal = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
type: "Post",
url: "/Calendar/dataReceiver",
dataType: "json",
data: { "title": eventData.title },
success: function (data) {
alert("successfull data send " + data);
},
error: function (req, status, error) {
alert(error + req + status);
}
});
},
eventClick: function (calEvent, jsEvent, view) {
alert(calEvent.title + calEvent.start + calEvent.end +obj)
},
dragOpacity: .50,
dragRevertDuration: 1000,
eventColor: '#378006',
eventBackgroundColor: 'gray',
editable: true,
eventStartEditable: true,
eventDurationEditable: true,
dragScroll: true,
eventOverlap: false,
eventLimit: true, // allow "more" link when too many events
events:
[
{
title: 'All Day Event',
start: '2015-02-01'
},
{
id: 999,
title: 'Repeating Event',
start: '2015-02-09T16:00:00'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2015-02-28'
}
]
});
},
error: function (req, status, error) {
alert(error + req + status);
var div = $('#SearchItemDiv');
div.html("");
div.append('Error');
}
});
}
Just added following line in questions and calendar renders:
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});
Hi i have DataTable which is binding to Gridview. But in need to bind that know to jqxgrid or jqxdatatable. After googling so many times i didn't got proper solution for this.
DataTable tb1= qry.GetTicketDetails();
serviceWindow.DataSource = tb;
serviceWindow.DataBind();
This what i'm doing actully now.
IN jquery i can take XML shown in below.
var source =
{
dataType: "json",
dataFields: [
{ name: 'name', type: 'string' },
{ name: 'type', type: 'string' },
{ name: 'calories', type: 'int' },
{ name: 'totalfat', type: 'string' },
{ name: 'protein', type: 'string' }
],
id: 'id',
url: "data/ticket.XML", //how to take datatable from code behind file
};
.aspx code -->>
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestCellSelection.aspx.cs" Inherits="CourierApp.Project.TestCellSelection" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title id='Description'></title>
<link rel="stylesheet" href="../JQWidgets/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../JQWidgets/scripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.columnsresize.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../JQWidgets/scripts/demos.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.pager.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxnumberinput.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxpanel.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.sort.js"></script>
<script type="text/javascript">
$(document).load(function () {
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#button").jqxButton({
theme: 'energyblue',
height: 30
});
$("#button").click(function () {
var cells = $('#jqxgrid').jqxGrid('getselectedcells');
var cellInfo = "";
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cellInfo += "\nRow: " + cell.rowindex + ", " + cell.datafield;
}
alert(cellInfo);
});
//GetData
var data = {};
var dataFelds = {};
var dataCols = {};
GetDatas();
GetCol_Datafeilds();
GetCol_Columns();
function GetDatas() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/GridValues")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
data = response;
console.log(data);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
function GetCol_Datafeilds() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/Col_Datafeilds")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
dataFelds = $.parseJSON(response);
console.log(dataFelds);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
function GetCol_Columns() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/Col_Columns")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
dataCols = $.parseJSON(response);
console.log(dataCols);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
// prepare the data
var source =
{
datatype: "json",
datafields: dataFelds,
updaterow: function (rowid, rowdata, commit) {
// synchronize with the server - send update command
// call commit with parameter true if the synchronization with the server is successful
// and with parameter false if the synchronization failder.
commit(true);
},
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
width: 1000,
source: dataAdapter,
editable: true,
selectionmode: 'multiplecellsadvanced',
columnsresize: true,
columns: dataCols
});
// $('#jqxgrid').jqxGrid('pincolumn', 'From_KG');
//$("#jqxgrid").jqxGrid('enablehover', event.args.checked);
});
<%--$("#<%=btn_SelectCells.ClientID%>").click(function () {
var cells = $('#jqxgrid').jqxGrid('getselectedcells');
var cellInfo = "";
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cellInfo += "\nRow: " + cell.rowindex + ", " + cell.datafield;
}
alert(cellInfo);
});--%>
</script>
</head>
<body class='default'>
<form id="form1" runat="server">
<div>
<div id='jqxWidget'>
<div id="jqxgrid">
</div>
</div>
<div style="margin-top: 10px;">
<input id="button" type="button" value="Get the selected cells" />
<%--<asp:Button ID="btn_SelectCells" runat="server" Text="Get the selected cells" UseSubmitBehavior="False" />--%>
</div>
</div>
</form>
</body>
</html>
.aspx.cs or Web Service Code ----->>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Web.Script.Serialization;
using System.Web.Helpers;
using BL;
using DAL;
using Newtonsoft.Json;
public partial class Project_Service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region Testing
[WebMethod]
public static String GridValues()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
String Val = serializer.Serialize(rows);
if (Val != "")
{
return (Val);
}
else
{
return "Error";
}
}
[WebMethod]
public static String Col_Datafeilds()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = new Dictionary<string, object>();
String Col = "";
int counter = 0;
foreach (DataColumn col in dt.Columns)
{
if (counter < 2)
{
row = new Dictionary<string, object>();
row.Add("name", col.ColumnName);
row.Add("type", "string");
rows.Add(row);
}
else if (counter >= 2)
{
row = new Dictionary<string, object>();
row.Add("name", col.ColumnName);
row.Add("type", "number");
rows.Add(row);
}
counter += 1;
}
Col = serializer.Serialize(rows);
//Col = JsonConvert.SerializeObject(rows);
if (Col != "")
{
return (Col);
}
else
{
return "Error";
}
}
[WebMethod]
public static String Col_Columns()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
String Col = "";
int counter = 0;
foreach (DataColumn col in dt.Columns)
{
if (counter < 2)
{
row = new Dictionary<string, object>();
row.Add("text", col.ColumnName.ToUpper());
row.Add("datafield", col.ColumnName);
row.Add("columntype", "textbox");
row.Add("width", "100");
row.Add("cellsalign", "left");
//row.Add("pinned", "true");
rows.Add(row);
}
else if (counter >= 2)
{
row = new Dictionary<string, object>();
row.Add("text", col.ColumnName.ToUpper());
row.Add("datafield", col.ColumnName);
row.Add("columntype", "textbox");
row.Add("width", "25");
row.Add("cellsalign", "right");
rows.Add(row);
}
}
Col = serializer.Serialize(rows);
// Col = JsonConvert.SerializeObject(rows);
if (Col != "")
{
return (Col);
}
else
{
return "Error";
}
}
#endregion
}
Paste it ......
Replace the Query by your Query.....
Donot Supply Datafeild and Column Def. in the .aspx page
It's Fully Dynamic Solution !!!
Im Currently Stack on how to display all the data of my database im new in using JQGRID and i dont know why is my data dont display when i deployed it on web using localhost
getdata.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Services;
using MySql.Data.MySqlClient;
public partial class getdata : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public struct s_GridResult
{
public int page;
public int total;
public int record;
public s_RowData[] rows;
}
public struct s_RowData
{
public int id;
public string[] cell;
}
[WebMethod]
public static s_GridResult GetDataTable(string _search, string nd, int rows, int page,
string sidx, string sord)
{
int startindex = (page - 1);
int endindex = page;
string sql = "SELECT ItemCode,PartNumber FROM tblitemcodefromqne";
DataTable dt = new DataTable();
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
adapter.Fill(dt);
s_GridResult result = new s_GridResult();
List<s_RowData> rowsadded = new List<s_RowData>();
int idx = 1;
foreach (DataRow row in dt.Rows)
{
s_RowData newrow = new s_RowData();
newrow.id = idx++;
newrow.cell = new string[2]; //total number of columns
newrow.cell[0] = row[0].ToString();
newrow.cell[1] = row[1].ToString();
rowsadded.Add(newrow);
}
result.rows = rowsadded.ToArray();
result.page = page;
result.total = dt.Rows.Count;
result.record = rowsadded.Count;
return result;
}
}
getdata.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/jquery-
ui-1.9.2.custom.css" />
<link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/ui.jqgrid.css" />
<link rel="Stylesheet" type="text/css" media="screen" href="Themes/style.css" />
<script type="text/javascript" src="JQGridReq/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="JQGridReq/jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="JQGridReq/jquery-ui-1.9.4.custom.min.js"></script>
<script type="text/javascript" src="JQGridReq/grid.locale-en.js"></script>
<script type="text/javascript" src="JQGridReq/jquery.jqGrid.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$.extend($.jgrid.defaults,
{ datatype: 'json' },
{ ajaxGridOptions: { contentType: "application/json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#Grid1")[0];
thegrid.addJSONData(data.d);
thegrid.grid.hDiv.loading = false;
switch (thegrid.p.loadui) {
case "disable":
break;
case "enable":
$("#load_" + thegrid.p.id).hide();
break;
case "block":
$("#lui_" + thegrid.p.id).hide();
$("#load_" + thegrid.p.id).hide();
break;
}
}
}
}
});
jQuery("#Grid1").jqGrid({
url: 'getdata.aspx/GetDataTable',
datatype: 'json',
mtype: 'POST',
colNames: ['Item Code', 'Part Number'],
colModel: [{ name: 'ItemCode', index: 'ItemCode', width: 200 },
{ name: 'PartNumber', index: 'PartNumber', width: 300}],
pager: '#pager', sortname: 'ItemCode',
viewrecoreds: true,
imgpath: 'JQGridReq/images',
serializeGridData: function (data) {
return $.toJSON(data);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="Grid1" class="scroll" align="center" width="100%"></table>
<div id="pager" class="scroll" style="text-align:center;">
</div>
</form>
</body>
</html>
The field names of the database table should match with the name in the colmodel which is in the javascript.
The java script
<script language="javascript" type="text/javascript">
$(function() {
var grid = jQuery("#myGrid");
grid.jqGrid({
url: "http://localhost:50530/jqGridHandler.ashx",
mtype:'GET',
datatype: "json",
height: 200,
hidegrid: false,//hides the arrow button at the top right corner for collapsing the jqGrid
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
caption: "Employees",
pager: "#pager",
colNames: ['FirstName', 'SecondName', 'DOB', 'EmailID','UserName'],
colModel: [
{ name: 'FirstName', index: 'FirstName', width: 100, align: "center" },
{ name: 'LastName', index: 'LastName', width: 100, align: "left" },
{ name: 'DOB', index: 'DOB', width: 100, align: "center", formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y' },
{ name: 'Email', index: 'EmailID', width: 120, align: "right"},
{ name: 'Username', index: 'Username', width: 100 }
]
});
});
</script>
the web component
<table id="myGrid"> </table>
the code behind (jqGridHandler.ashx)
public class jqGridHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
MyFirstService.Service1Client client = new MyFirstService.Service1Client();
context.Response.Write(client.GetJsonUsers());
}
private DataSet GetUsersFromDB()
{
AccessDataBase reader = new AccessDataBase();
string selectquery = "SELECT * FROM Registration";
return reader.readDB(selectquery);
}
public string GetJsonUsers()
{
return GetJson(GetUsersFromDB());
}
private string GetJson(DataSet dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataTable dtt in dt.Tables)
foreach (DataRow dr in dtt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
public bool IsReusable
{
get
{
return false;
}
}
}
AccessDB.cs
public SqlConnection Connection { get; set; }
public AccessDataBase()
{
Connection = new SqlConnection("Data Source=.;Initial Catalog=NewDB;Integrated Security=True");
}
public DataSet readDB(string selectquery)
{
SqlCommand cmd = new SqlCommand(selectquery);
using (Connection)
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = Connection;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
and add
using System.Web.Script.Serialization;
and don forget to add the js and css files in the master page.
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Scripts/JQGrid/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<link href="Scripts/JQGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/JQGrid/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/jquery.jqGrid.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>
I found out the answer by my self here's what i did to implement JQGrid on ASP.net and MySQL database.
ItemCode.ashx
public struct JQGridResults
{
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow
{
public string ItemCode;
public string PartNumber;
public string ItemDescriptionShort;
public string ItemDescriptionLong;
public string ProductCode;
public string GroupCode;
public string BusinessUnit;
public string[] cell;
}
[Serializable]
public class User
{
public string ItemCode { get; set; }
public string PartNumber { get; set; }
public string ItemDescriptionShort { get; set; }
public string ItemDescriptionLong { get; set; }
public string ProductCode { get; set; }
public string GroupCode { get; set; }
public string BusinessUnit { get; set; }
}
public class ItemCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = request["_search"];
string numberOfRows = request["rows"];
string pageIndex = request["page"];
string sortColumnName = request["sidx"];
string sortOrderBy = request["sord"];
int totalRecords;
Collection <User> users = GetUsers(numberOfRows, pageIndex, sortColumnName,sortOrderBy, out totalRecords);
string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows),Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write(output);
}
private string BuildJQGridResults(Collection <User> users, int numberOfRows, int pageIndex, int totalRecords)
{
JQGridResults result = new JQGridResults();
List<JQGridRow> rows = new List<JQGridRow>();
foreach (User user in users)
{
JQGridRow row = new JQGridRow();
row.ItemCode = user.ItemCode;
row.PartNumber = user.PartNumber;
row.ItemDescriptionShort = user.ItemDescriptionShort;
row.ItemDescriptionLong = user.ItemDescriptionLong;
row.ProductCode = user.ProductCode;
row.GroupCode = user.GroupCode;
row.BusinessUnit = user.BusinessUnit;
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = (totalRecords + numberOfRows - 1) / 8;
result.records = totalRecords;
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
//return new JavaScriptSerializer().Serialize(result);
return serializer.Serialize(result);
}
private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
{
Collection<User> users = new Collection<User>();
MySqlConnection conn = Functions.GetConnection();
string sql;
sql = "SELECT * FROM swans.tblsomain,tblligerstatus;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader data1 = cmd.ExecuteReader();
string connectionString = "server=127.0.0.1;database=swans;uid=root;password=''";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandText = "select ItemCode,PartNumber,ItemDescriptionShort,ItemDescriptionLong,ProductCode,GroupCode,BusinessUnit from tblitemcodefromqne;";
command.CommandType = CommandType.Text;
MySqlParameter paramPageIndex = new MySqlParameter("#PageIndex",MySqlDbType.Int32);
paramPageIndex.Value = Convert.ToInt32(pageIndex);
command.Parameters.Add(paramPageIndex);
MySqlParameter paramColumnName = new MySqlParameter("#SortColumnName", MySqlDbType.VarChar, 50);
paramColumnName.Value = sortColumnName;
command.Parameters.Add(paramColumnName);
MySqlParameter paramSortorderBy = new MySqlParameter("#SortOrderBy", MySqlDbType.VarChar, 4);
paramSortorderBy.Value = sortOrderBy;
command.Parameters.Add(paramSortorderBy);
MySqlParameter paramNumberOfRows = new MySqlParameter("#NumberOfRows", MySqlDbType.Int32);
paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
command.Parameters.Add(paramNumberOfRows);
MySqlParameter paramTotalRecords = new MySqlParameter("#TotalRecords",MySqlDbType.Int32);
totalRecords = 0;
paramTotalRecords.Value = totalRecords;
paramTotalRecords.Direction = ParameterDirection.Output;
command.Parameters.Add(paramTotalRecords);
connection.Open();
using (MySqlDataReader dataReader = command.ExecuteReader())
{
User user;
while (dataReader.Read())
{
user = new User();
user.ItemCode = Convert.ToString(dataReader["ItemCode"]);
user.PartNumber = Convert.ToString(dataReader["PartNumber"]);
user.ItemDescriptionShort = Convert.ToString(dataReader["ItemDescriptionShort"]);
user.ItemDescriptionLong =Convert.ToString(dataReader["ItemDescriptionLong"]);
user.ProductCode = Convert.ToString(dataReader["ProductCode"]);
user.GroupCode = Convert.ToString(dataReader["GroupCode"]);
user.BusinessUnit = Convert.ToString(dataReader["BusinessUnit"]);
users.Add(user);
}
}
totalRecords = users.Count;
}
return users;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
ItemCode.aspx
<script type="text/javascript" >
$(function () {
$("#UsersGrid").jqGrid({
type: 'POST',
url: 'ItemCode.ashx',
datatype: "json",
width: 1245,
height: 450,
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "total",
records: "records"
},
colNames: ['Item Code', 'Part Number', 'Short Description', 'Long Description', 'Product Code', 'Group Code', 'Business Unit'],
colModel: [
{ name: 'ItemCode', index: 'ItemCode', width: 60, editable:true, sorttype: 'string' },
{ name: 'PartNumber', index:'PartNumber', width: 50 },
{ name: 'ItemDescriptionShort',index:'ItemDescriptionShort', width: 260 },
{ name: 'ItemDescriptionLong',index:'ItemDescriptionLong', width: 260 },
{ name: 'ProductCode',index:'ProductCode', width: 50 },
{ name: 'GroupCode',index:'GroupCode', width: 50 },
{ name: 'BusinessUnit',index:'BusinessUnit', width: 50 },
],
cmTemplate: { title: false },
rowNum: 20,
mtype: 'GET',
loadonce: true,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: 'ItemCode',
multiSort: true,
gridview: true,
viewrecords: true,
sortorder: 'asc',
caption: "Item Code Summary"
});
jQuery("#UsersGrid").jqGrid('navGrid', '#UsersGridPager',
{ del: false, add: false, edit: false, search: false });
jQuery("#UsersGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });
});
</script>
</head>
<body>
<form id="UsersForm" runat="server">
<table id="UsersGrid" ></table>
<div id="UsersGridPager"></div>
</form>
</body>