Populate chart.js from data table / SQL result set - c#

Based on an SQL result set, I intend to populate a data table, meant to serve as datasource for a chart (using chart.js).
Any idea on how should I make this work using C# / ASP.NET as I did not found any working examples?
Many thanks

I've created the following Javascript method which is called from the backend
function FillBarChart(names, values, canvasId, graphTitle, labels) {
var color = Chart.helpers.color;
var colors = '#' + Math.floor(Math.random() * 16777215).toString(16);
var collors = 'hsla(' + (Math.floor(Math.random() * 360) + ', 70%, 70%, 1)');
var chartData = {
labels: names.split(','),
datasets: [
{
label: labels,
backgroundColor: collors,
borderColor: color("#0061ff"),
borderWidth: 1,
data: values.split(',')
}
]
};
var ctx = document.getElementById(canvasId).getContext('2d');
window.barChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: graphTitle
}
}
});
}
The C# lines that trigger this are the following:
StringBuilder javascriptCommands = new StringBuilder();
HtmlGenericControl canvas = new HtmlGenericControl();
canvas.TagName = "canvas";
canvas.Attributes["Height"] = CanvasHeight;
canvas.ClientIDMode = ClientIDMode.Static;
canvas.ID = "canvasSales";
string graphNames = "Previous Year,Current Year";
string graphValues = MainSession.salesPY + "," + MainSession.salesCY;
charts.Controls.Add(canvas);
javascriptCommands.Append("FillBarChart(`" + graphNames + "`,`" + graphValues + "`,`" + canvas.ID + "`,`" + "Grand Total Sales" + "`,`" + "Total Sales Graph" + "`);");
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mykey", javascriptCommands.ToString(), true);
MainSession.salesPY and MainSession.salesCY are the needed values, brought from SQL in my case and concatenated as strings, sepparated with a comma.

Related

MVC Razor, LINQ into J-Query?

What is the best way to pass a LINQ value into J-Query???... How would I go about this?
When the Update link is clicked, it checks the web Grid to see if it is the same on TrailerNumber and CarrierName. If the inputs are the same in both fields as already existing, then allows you to move the data to the current row. (avoid duplication)
Any help would be greatly appreciated!
Checks to see is the inputs already exist in TrailerNumber and CarrierName as the same.
LINQ (Controller):
bool AlreadyInTable = entities.LocationDataMasters.Any(t => t.TrailerNumber == customer.TrailerNumber && t.CarrierName == customer.CarrierName);
//Update event handler.
$("body").on("click", "#webGrid TBODY .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
row.find(".Clear").show();
$(this).hide();
var customer = {};
customer.LocationID = row.find(".LocationID").find(".label").html();
customer.UserName = row.find(".UserName").find(".label").html();
customer.Location = row.find(".Location").find(".label").html();
customer.Section = row.find(".Section").find(".label").html();
customer.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
customer.CarrierName = row.find(".CarrierName").find(".label").html();
customer.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
customer.DateLoaded = row.find(".DateLoaded").find(".label").html();
customer.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}) //setInterval('location.reload()', 777);
/*************************** Added to Find Duplicates ******************************/
/***********************************************************************************/
/***********************************************************************************/
//(1)Finds the Current Row selected with Edit Link:
var CurrentLocationID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentLocation = $(this).closest('tr').find("#LocationLbl").text();
var CurrentSection = $(this).closest('tr').find("#SectionLbl").text();
var CurrentTrailerNumber = $(this).closest('tr').find("#TrailerNumberLbl").text();
var CurrentTrailerNumberVal = $(this).closest('tr').find("#TrailerNumber").val();
var CurrentCarrrierNameLbl = $(this).closest('tr').find("#CarrierNameLbl").text();
var CurrentCarrrierName = $(this).closest('tr').find("#CarrierName").val();
var CurrLocationID = $(this).closest('tr').find("#LocationID").val();
var CurrentIDTrailerCarrier = 'Current Row Location, LocationID: ' + CurrentLocationID + ' Location: ' + CurrentLocation + ' Section: ' + CurrentSection + ' TrailerNumber: ' + CurrentTrailerNumber + ' CarrierName: ' + CurrentCarrrierName;
var TrailerNumberRows = $('#webGrid tr').find("#TrailerNumber").val();
//Identify the current row data to find duplicates against.
/// alert("CurrentIDTrailerCarrier: " + CurrentIDTrailerCarrier);
// $('#webGrid TR').each(function (row, x) {
//=========== This decision is what determines to check for duplicates. ==============
//Loop through Rows that contain the same Trailer Number and Count Rows:
var TrailerNumberContainsCount = $("#webGrid tr > td #TrailerNumberLbl:contains('" + CurrentTrailerNumber + "')").parent().length;
var CarrierNameContainsCount = $("#webGrid tr > td.CarrierName:contains('" + CurrentCarrrierNameLbl + "')").parent().length;
/// alert("TrailerNumberContainsCount: " + TrailerNumberContainsCount + " CarrierNameContainsCount: " + CarrierNameContainsCount);
**if (TrailerNumberContainsCount > 1 && $("#webGrid tr > td #TrailerNumberLbl:contains('" + CurrentTrailerNumber + "')") && $("#webGrid tr > td.CarrierName:contains('" + CurrentCarrrierNameLbl + "')") && CarrierNameContainsCount > 1 ) {**
/****************************************************************/
/************** Find Duplicates Get the LocationID **************/
/****************************************************************/
//Hide rows on TrailerNumber & CarrierName that don't match.
$("#webGrid tr > td #TrailerNumberLbl:not(:contains('" + CurrentTrailerNumber + "'))").filter(':visible').parents().closest('TR').hide();
$("#webGrid tr > td #CarrierNameLbl:not(:contains('" + CurrentCarrrierNameLbl + "'))").filter(':visible').parent().closest('TR').hide(); //Hide Rows that don't contain value.
//Take out the ID that is on the current row to show the duplicate ID only.
var DuplicateID = $('#webGrid tr').filter(':visible').find("#LocationIDLbl:not(:contains('" + CurrentLocationID + "'))").text();
DuplicatesVisibleID = DuplicateID;
//Call the DuplicateID Row to be colored Yellow where the duplicate exists:
$("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible').attr('style', 'background-color:#FFFF00;');
$('#webGrid tr:first').parent().show(); //Always show the header.
/********************************************************/
/****************** Start Selection *********************/
/********************************************************/
///$('.SelectedMoveToChecked').attr('disabled', true);
//Allow only one selection of the row to be checked on a checkbox.
$('.SelectedMoveToChecked').click('td', function () {
$(".SelectedMoveIsChecked").not(this).prop('checked', false);
$(".SelectedMoveToChecked").not(this).prop('checked', false);
});
//$(this).closest('tr').find('.RowLocationDupDropDownList').removeAttr('disabled');
$(".SelectedMoveIsChecked").filter(':visible').hide();
$(this).closest("tr").find(".SelectedMoveToChecked").show();
//$('.RowLocationDupDropDownList').hide();
//Gather the data from the row that has the LocationID that is the Duplicate.
var DupRow = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible');
var DupLocation = DupRow.find('#LocationLbl').text();
var DupSection = DupRow.find('#SectionLbl').text();
var DupTrailerNumber = DupRow.find('#TrailerNumberLbl').text();
var DupCarrierName = DupRow.find('#CarrierNameLbl').text();
var DupLoadCommodityStatus = DupRow.find('#LoadCommodityStatusLbl').text();
var DupDateLoaded = DupRow.find('#DateLoadedLbl').text();
var DupUserName = DupRow.find('#UserNameLbl').text();
var DupPlantLocation = DupRow.find('#PlantLocationLbl').text();
/// alert("DupLocationID: " + DuplicatesVisibleID + " DupLocation: " + DupLocation + " DupSection: " + DupSection + " DupTrailerNumber: " + DupTrailerNumber + " DupCarrierName: " + DupCarrierName);
$(".RowLocationDupDropDownList").hide();
// var $actualRow = $(row);
let text = DupSection + ' ' + DupLocation + ' ' + DuplicatesVisibleID;
$("select option").filter(function () {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
$(".SelectedMoveToChecked").change(function () {
/// e.preventDefault();
//$('select.RowLocationDupDropDownList').each(function () {
if ($("select.SelectedMoveToChecked").closest('checked', true)) {
$(this).closest("tr").find('.RowLocationDupDropDownList').attr('disabled', true).show();
}
if ($('select.SelectedMoveToChecked').closest('checked', false)) {
$('.SelectedMoveToChecked').closest('checked', false).css('visibility', 'hidden');
}
$('select.RowLocationDupDropDownList').children("option:selected").text(DupSection + ' ' + DupLocation + ' ' + DuplicatesVisibleID);
/**********************************************************/
/********** Start Confirmation Dialogue Options ***********/
/**********************************************************/
if ($(this).children("option:selected").val() != '') {
function DuplicateMoveConfirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this? \n" + " TrailerNumber: " + DupTrailerNumber + " CarrierName: " + DupCarrierName + " \n\n " + " From Duplicate Row: \n"
+ " Section: " + DupSection + " Location:" + DupLocation + " Row ID:" + DuplicatesVisibleID + " \n\n ";
if (confirm("Confirm Move Aready Existing To Current Row! " + ConfirmStr + "To Current Row: \n" + " Section: " + CurrentSection + " Location: " + CurrentLocation + " Row ID: " + CurrentLocationID + "?")) {
confirm_value.value = "Yes";
//Trigger/Handler from Drop-Down Box Change.
$("body").on("change", ".SelectedMoveToChecked", function () {
// $("body").on("change", "#TrailerNumber", function (e) {
// e.preventDefault();
/// var row = $(this).closest("tr");
var row = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible'); //Focus on the other row, not current row.
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum) 9 Items where data comes from.
var ToRow = {};
// ToRow.LocationID = RowLocationIDNum;
ToRow.LocationID = CurrentLocationID;
//ToRow.LocationID = DuplicatesVisibleID;
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
/// var row = $(this).closest("tr");
var row = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible'); //Focus on the other row, not current row.
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
})
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
//Clear Duplicate Row After Moving the Data to the Current Row.
// clear.LocationID = DuplicatesVisibleID;
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
})
}
})
setInterval('location.reload()', 777);
})
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 777);
}
document.forms[0].appendChild(confirm_value);
}
DuplicateMoveConfirm();
}
});
}
});
//It finds when both TrailerNumber and CarrierName, but also finds when just TrailerNumber, even though CarrierName is not the same.

How to print a map that uses the google maps API on a PDF using Rotativa?

I am using Rotativa in order to obtain a PDF containing information that is previously shown on a Modal, nevertheless, when the user clicks on the button to obtain the PDF, this one does not contain a map that uses the google maps API, is there any way to solve this?
Here is the Modal that is previously shown to the user with the information:
This is the PDF, notice that PDF is not printing the map and it should be there:
Here is my code:
Front-end code
var map = new google.maps.Map($('#map')[0], {
center: { lat: 19.397, lng: -99.144 },
zoom: 10
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(19.397, -99.144),
map: map,
title: ""
});
var bounds = new google.maps.LatLngBounds();
google.maps.event.trigger(map, "resize");
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
marker.setPosition(LatLng);
google.maps.event.trigger(map, 'resize');
map.setCenter(LatLng);
map.setZoom(18);
/*Poligonos*/
var rut = $("#txt_Ruta").val();
var ced = $("#txt_Cedis").val();
var frecu = CosasModal.orden.Frecuencia;
var jqxhr = $.post("/Poligonos/ObtenerPoligono", { "Ruta": rut, "Frecuencia": frecu, "Cedis": ced },
function (data) {
if (data.status == "OK") {
var Poligono = new google.maps.Polyline({
path: data.coordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
Poligono.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: "Ruta " + rut + "<br>Frecuencia: " + frecu + "<br>Cedis: " + ced
});
google.maps.event.addListener(Poligono, 'click', function (event) {
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
var points = Poligono.getPath().getArray();
for (var n = 0; n < points.length; n++) {
bounds.extend(points[n]);
}
map.fitBounds(bounds);
}
});
jqxhr.fail(function () {
//alert("Error de comunicaciĆ³n con el servidor.");
swal("Error", "Error de comunicaciĆ³n con el servidor.", "error");
});
map.fitBounds(bounds);
map.panToBounds(bounds);
/*fin poligonos*/
Rotativa code (imagine that you receive idOrden variable)
var pdf = new ActionAsPdf("ModalPedidosPdfView", new { idOrden = idOrden })
{
FileName = "ReporteOrdenIndividual" + DateTime.Now.ToString() + "_" + idOrden
};
return pdf;
I solved my problem using Select.pdf instead of Rotativa

How to add a conditional statement to assign a value inside C# lambda select list query?

I have a working lambda query that gets list data for nearby map points. The FoodType value indicates what group the restaurant is part of, like this: 3 - Italian, 1 - Mexican, 4 - Indian.
How can I add a conditional if statement to the query that would assign a different colored icon for that map point, based on their FoodType value.
I want
1 - Mexican to be Icon = "../Images/red-dot.png"
3 - Italian to be Icon = "../Images/yellow-dot.png"
5 - Asian to be Icon = "../Images/blue-dot.png"
Here is my Controller code:
[HttpPost]
public ActionResult Index(float latitude, float longitude)
{
var sourcePoint = CreatePoint(latitude, longitude);
var locations = db.Restaurants
.Where(loc => loc.GeoLocation.Distance(sourcePoint) < 1500)
.OrderBy(loc => loc.GeoLocation.Distance(sourcePoint))
.Select(loc => new MapViewModel
{
Address = loc.PrimaryAddress1,
City = loc.PrimaryCity,
HHName = loc.HHName,
Age = loc.Age,
FoodType = loc.FoodType,
Id = loc.Id,
Latitude = (float)loc.Latitude,
Longitude = (float)loc.Longitude,
Distance = loc.GeoLocation.Distance(sourcePoint),
})
.ToList();
return Json(locations, JsonRequestBehavior.AllowGet);
}
Here is my Map code:
(I have even tried setting the map point color inside the script without success)
$.ajax({
type: "POST",
url: "Index/",
data: { "latitude": latitude, "longitude": longitude, 'address': address },
dataType: "json",
position: latLng,
center: latLng,
success: function(data) {
$.each(data, function(index, value) {
var latlng = new google.maps.LatLng(value.Latitude, value.Longitude);
var marker = new google.maps.Marker({
position: latlng,
icon: "../Images/blue-dot.png",
title: value.HHname,
address: value.Address,
city: value.City,
food: value.FoodType,
age: value.Age,
id: value.id,
map: map
});
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + value.HHName + '</h1>' +
'<div id="bodyContent">' +
'<p><b>' + value.FoodType + '</b></p>' +
'<p>Age:' + value.Age + '</b></p>' +
'<p><b>' + value.Address + ', ' + value.City + '</b></p>' +
'<p><a class="btn btn-danger" href="#">More Info' +
'</a> ' +
'</p>' +
'</div>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
maxWidth: 250,
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
},
});
If you're using LINQ-to-Entities or Entity Framework, then you can't use a custom method in the query because the underlying provider expects to be able to translate the query expression directly into SQL. If you're getting an error saying the method is not recognized, that is why. You can only use methods that the underlying provider knows how to translate. With this in mind, there are a few different approaches you could take.
1. Use the ternary operator to calculate the value
It's a bit ugly, but it should work because it can be translated to a SQL CASE expression.
var locations = db.Restaurants
.Where(...)
.OrderBy(...)
.Select(loc => new MapViewModel
{
...
FoodType = loc.FoodType,
Icon = "../Images/" +
(loc.FoodType == "1 - Mexican" ? "red" :
(loc.FoodType == "3 - Italian" ? "yellow" : "blue")) +
"-dot.png",
...
})
.ToList();
2. Run the query, then fix up the results before returning it to the client
This is the usual workaround when you need to run a server-side method to include calculated data in your results and that method is not supported by LINQ-to-Entities.
// DB query
var locations = db.Restaurants
.Where(...)
.OrderBy(...)
.Select(loc => new MapViewModel
{
...
FoodType = loc.FoodType,
...
})
.ToList();
// Fix up
foreach (var model in locations)
{
model.Icon = GetIconForFoodType(model.FoodType);
}
return Json(locations, JsonRequestBehavior.AllowGet);
3. Change your data model to include the icon image name in the table
If the icon name is part of the table data, then there's no translation needed; you can just include it directly in the result.
var locations = db.Restaurants
.Where(...)
.OrderBy(...)
.Select(loc => new MapViewModel
{
...
FoodType = loc.FoodType,
Icon = "../Images/" + loc.IconName
...
})
.ToList();
For readability and reusability write a separate function that converts the FoodType value to its corresponding icon.
string GetIconForFoodType(string foodType)
{
//Your function
}
Then when creating your MapViewModel, assign
Icon = GetIconForFoodType(loc.FoodType)
Brian's answer #1 really helped me. In case it helps anyone here is my implementation which works perfectly below. It's what as he suggested.
#Html.DropDownList("TaxonId", Model.Taxa.Select(i => new SelectListItem()
{
Text = i.TaxonName,
Value = i.Id.ToString(),
Selected = (i.Id == #Model.Site.TaxonId) ? true : false
}),
"Select taxon",
new { #class = "form-control edited", required = String.Empty })

Recover id in display list using combobox

i need to recover the id of element selected in combobox in dev express
and this is the code of combobox:
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "comboBox4";
settings.Width = 180;
settings.SelectedIndex = 0;
settings.Properties.DropDownWidth = 550;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Editors", Action = "MultiColumnComboBoxPartial" };
settings.Properties.CallbackPageSize = 30;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
settings.Properties.TextFormatString = "{1}";
settings.Properties.ValueField = "Id";
settings.Properties.ValueType = typeof(string);
settings.Properties.Columns.Add("Id", "Id", 130).SetColVisible(false);
// settings.Properties.Columns.Add("Id", "Id", 130).SetColVisibleIndex(1);
settings.Properties.Columns.Add("Nom", "Nom", 130);
settings.Properties.Columns.Add("Prenom", "Prenom", Unit.Percentage(100));
settings.Properties.Columns.Add("DateNaissance", "DateNaissance", 60);
settings.Properties.Columns.Add("CodeClient", "CodeClient", 100);
}
).BindList(client).GetHtml()
and this the method ajax how i put the value of any custom with ajax:
function Addprojet() {
debugger;
var nom = $("#nom2_I").val();
var description = $("#Description_I").val();
var client = $("#comboBox4_I").val();
var chef = $("#chefid_I").val();
var complexite = $("#comboBox1_I").val();
var taille = $("#comboBox2_I").val();
var datedebut = $("#datedebut_I").val();
$.ajax({
url: "/Projet/AjouterProjet?nom=" + nom + "&description=" + description + "&client=" + client + "&chef=" + chef + "&complexite=" + complexite + "&taille=" + taille + "&datedebut=" + datedebut, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
location.replace("/Client/listeclients");
}
else {
alert("error");
}
}
});
}
</script>
how can i resolve this issue because i need to recover the id of client without displaying in the list in the combobox
can semeone help me to fix it .

How to customize Google charts from code using C#?

I am using google charts for my asp.net web application. I have successfully got the chart working in my application. But I want to know how to add animation, change the color of the column chart from code. In javascript I know it can be done using below option -
var options = {
width: 400,
height: 240,
title: 'Sample Data',
colors: ['#e0440e', '#f6c7b6'],
is3D:true
};
I tried calling the same in c# using string builder but chart itself doesnot load. Here is my code-
private void BindCourseChart()
{
//to bind course chart
DataTable dt = new DataTable();
try
{
dt = GetData_Course();
str.Append(#"<script type=text/javascript> google.load( *visualization*, *1*, {packages:[*corechart*],callback:drawChart});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Title');
data.addColumn('number', 'Users enrolled');
**//Here I am adding role=style for customizing**
data.addColumn({type: 'string', role: 'style'});
data.addRows(" + dt.Rows.Count + ");");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i] ["Title"].ToString() + "');");
str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["MenteeCount"].ToString() + ") ;");
}
str.Append(" var chart = new google.visualization.ColumnChart(document.getElementById('course_div'));");
str.Append(" chart.draw(data, {width: 650, height: 300, title: 'Course Enrollment', color:#0092CB,");
str.Append("hAxis: {title: 'Course Title', titleTextStyle: {color: 'green'}}");
str.Append("}); }");
str.Append("</script>");
lt_course.Text = str.ToString().TrimEnd(',').Replace('*', '"');
}
Can anyone help me in this regard how to add colors,or animation to column charts .
Thanks in advance
If interested, I made a Google Chart class awhile back that I've used in a few projects:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Google
{
/// <summary>
/// Summary description for GoogleChart
/// </summary>
public class GoogleChart
{
// Fields
private string data = "";
private string javascript;
// Properties
public string elementId { get; set; }
public int height { get; set; }
public string title { get; set; }
public int width { get; set; }
// ChartTypes
public enum ChartType
{
BarChart,
PieChart,
LineChart,
ColumnChart,
AreaChart,
BubbleChart,
CandlestickChart,
ComboChart,
GeoChart,
ScatterChart,
SteppedAreaChart,
TableChart
}
// Methods
public GoogleChart()
{
this.title = "Google Chart";
this.width = 730;
this.height = 300;
this.elementId = "chart_div";
}
public void addColumn(string type, string columnName)
{
string data = this.data;
this.data = data + "data.addColumn('" + type + "', '" + columnName + "');";
}
public void addRow(string value)
{
this.data = this.data + "data.addRow([" + value + "]);";
}
public string generateChart(ChartType chart)
{
this.javascript = "<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>";
this.javascript = this.javascript + "<script type=\"text/javascript\">";
this.javascript = this.javascript + "google.load('visualization', '1.0', { 'packages': ['corechart']});";
this.javascript = this.javascript + "google.setOnLoadCallback(drawChart);";
this.javascript = this.javascript + "function drawChart() {";
this.javascript = this.javascript + "var data = new google.visualization.DataTable();";
this.javascript = this.javascript + this.data;
this.javascript = this.javascript + "var options = {";
this.javascript = this.javascript + "'title': '" + this.title + "',";
object javascript = this.javascript;
this.javascript = string.Concat(new object[] { javascript, "'width': ", this.width, ", 'height': ", this.height, "};" });
string str = this.javascript;
this.javascript = str + "var chart = new google.visualization." + chart.ToString() + "(document.getElementById('" + this.elementId + "'));";
this.javascript = this.javascript + "chart.draw(data, options);";
this.javascript = this.javascript + "} </script>";
return this.javascript;
}
}
}
You can then use it by doing the following:
private void GenerateQuickStats()
{
GoogleChart chart = new GoogleChart();
chart.title = "Quick Stats";
chart.width = 250;
chart.height = 200;
chart.addColumn("string", "Year");
chart.addColumn("number", "Value");
chart.addColumn("number", "Profit");
chart.addRow("'2014', 2000, 1000");
// asp literal
ltChart.Text = chart.generateChart(GoogleChart.ChartType.ColumnChart);
}
Since David addressed the color issue, I'll tackle the animations. Animating the chart on first draw is a bit complicated; you have to draw it once with a zero'd out data set, and then draw it again with the real data set. Here's some javascript (that you can add to your string builder, replacing the chart creation and drawing lines) that will animate the chart:
var view = new google.visualization.DataView(data);
view.setColumns([0, {
sourceColumn: 1,
calc: function () {return 0;}
}, 2]);
var chart = new google.visualization.ColumnChart(document.getElementById('course_div'));
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
chart.draw(data, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
});
chart.draw(view, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
[Edit - attempt at C# example]
private void BindCourseChart()
{
//to bind course chart
DataTable dt = new DataTable();
try
{
dt = GetData_Course();
str.Append(#"
<script type=text/javascript>
google.load( *visualization*, *1*, {packages:[*corechart*], callback:drawChart});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Title');
data.addColumn('number', 'Users enrolled');
**//Here I am adding role=style for customizing**
data.addColumn({type: 'string', role: 'style'});
data.addRows(" + dt.Rows.Count + ");
");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i] ["Title"].ToString() + "');");
str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["MenteeCount"].ToString() + ") ;");
}
str.Append(#"
var view = new google.visualization.DataView(data);
view.setColumns([0, {
sourceColumn: 1,
calc: function () {return 0;}
}, 2]);
var chart = new google.visualization.ColumnChart(document.getElementById('course_div'));
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
chart.draw(data, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
});
chart.draw(view, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
}
</script>
");
lt_course.Text = str.ToString().TrimEnd(',').Replace('*', '"');
}
I believe you are missing quotation marks around your color...
At the end of this line:
str.Append(" chart.draw(data, {width: 650, height: 300, title: 'Course Enrollment', color:#0092CB,");
you need apostrophes around the hex color:
str.Append(" chart.draw(data, {width: 650, height: 300, title: 'Course Enrollment', color:'#0092CB',");
If that doesn't work, compare the javascript that your app generates with your manually created code.

Categories

Resources