Skip to main content

ChartJS3

Namespace: Wisej.Web.Ext.ChartJS3

Assembly: Wisej.Web.Ext.ChartJS3 (4.1.0.0)

ChartJS3 is a simple yet flexible JavaScript charting library for designers and developers from http://www.chartjs.org/.

public class ChartJS3 : Widget

The control wraps Chart.js 3.5.0 and the chartjs-plugin-datalabels plugin. Configure the chart using ChartType, Options, Labels and DataSets. Changing any of them redraws the whole chart on the client. To change only the data values with an animated transition, call UpdateData. The chart is always responsive and fills the control: the client sets the Chart.js options responsive to true and maintainAspectRatio to false.

Example:

private void Page1_Load(object sender, EventArgs e)
{
this.chartJS31.ChartType = ChartType.Bar;
this.chartJS31.Labels = new[] { "Jan", "Feb", "Mar", "Apr" };

var sales = this.chartJS31.DataSets.Add("Sales");
sales.Data = new object[] { 120, 95, 140, 110 };
}

Constructors​

Instance member ChartJS3()​

Constructs a new instance of the ChartJS3 control.

The new control uses the Line chart type and has no labels and no data sets.

Example:

var chart = new ChartJS3();
chart.Dock = DockStyle.Fill;
chart.ChartType = ChartType.Pie;
chart.Labels = new[] { "Red", "Green", "Blue" };
chart.DataSets.Add("Votes").Data = new object[] { 12, 19, 7 };
this.Controls.Add(chart);

Properties​

Instance member ChartType​

ChartType: Returns or sets the ChartType of the chart. (Default: Line)

Value: One of the ChartType values. The default is Line.

Changing the chart type replaces Options with a new instance specific for the new type (i.e. BarOptions for Bar and HorizontalBar), copying the shared options from the previous instance. It also replaces DataSets with a new collection of data sets matching the new type, copying the properties that the old and new data set classes have in common. Bubble and Scatter charts use LineDataSet data sets. Then the chart is redrawn. Set the chart type before configuring the options and the data sets, since references to the previous instances are no longer used by the chart.

Chart.js 3 has no horizontal bar type: HorizontalBar is rendered as a bar chart. Set IndexAxis to "y" to draw the bars horizontally.

Example:

this.chartJS31.ChartType = ChartType.Doughnut;

// the options are now an instance of DoughnutOptions.
var options = (DoughnutOptions)this.chartJS31.Options;
options.Cutout = 60;

Instance member DataSets​

DataSetCollection: Returns the data sets to plot the chart.

Value: A DataSetCollection containing the DataSet objects to plot.

The collection is created automatically and is recreated when ChartType changes. Use Add to create a data set of the type that matches the current chart type. Adding, removing or replacing data sets redraws the chart. To animate changes to the values of existing data sets, change their Data and call UpdateData.

Example:

this.chartJS31.DataSets.Clear();

var revenue = (LineDataSet)this.chartJS31.DataSets.Add("Revenue");
revenue.Data = new object[] { 10, 22, 15, 30 };
revenue.BorderColor = Color.SteelBlue;
revenue.Fill = false;

Instance member InitScript​

String: Overridden to return the initialization script that creates the Chart.js chart on the client.

The script is loaded from the embedded resource "Wisej.Web.Ext.ChartJS3.JavaScript.startup.js". It registers the datalabels plugin, converts the options and data sets to the Chart.js 3 format and attaches the click handler that fires ChartClick. Assigning a value has no effect.

Example:

// a derived chart that adds a client-side function to the widget.
public class MyChart : ChartJS3
{
public override string InitScript
{
get { return base.InitScript + "\r\nthis.refresh = function() { this.chart.update(); };"; }
set { }
}
}

Instance member Labels​

String[]: Returns or sets the labels for the data points.

Value: An array of strings. The default is an empty array; setting it to null assigns an empty array.

Each label corresponds to the value at the same index in the Data array of each data set. Setting this property redraws the chart. At design time, when there are no data sets with data, the designer draws a sample data set with random values, one for each label.

Example:

this.chartJS31.Labels = new[] { "Q1", "Q2", "Q3", "Q4" };
this.chartJS31.DataSets.Add("Profit").Data = new object[] { 4.2, 5.1, 3.8, 6.0 };

Instance member Options​

Options: Returns or sets the chart options specific for the value of ChartType. (Default: null)

Value: An Options instance. When the chart type is Line it is a LineOptions, when it is Bar or HorizontalBar it is a BarOptions, and so on.

The options are created automatically when first read and are recreated when ChartType changes. They are sent to the client as the Chart.js options object, using camel case property names and omitting null values. On the client, the axes in xAxes and yAxes are converted to the Chart.js 3 scales object using the ids "x0", "x1", ... and "y0", "y1", ..., and the options in Plugins are passed to the title, legend, tooltip and datalabels plugins. Assigning a new instance attaches it to this control and redraws the chart. The assigned instance should match the current ChartType. This property hides the inherited Options property.

Throws:

Example:

this.chartJS31.ChartType = ChartType.Line;
this.chartJS31.Options.Plugins.Title.Display = true;
this.chartJS31.Options.Plugins.Title.Text = "Monthly Visitors";
this.chartJS31.Options.Plugins.Legend.Position = HeaderPosition.Bottom;

// or replace the whole set of options.
this.chartJS31.Options = new LineOptions { Stacked = true };

Instance member Packages​

List<Package>: Overridden to return the list of script resources required by the chart.

The first time it is read, the list is filled with moment.js 2.29.4, Chart.js 3.5.0 and chartjs-plugin-datalabels, all loaded from the resources embedded in the extension assembly.

Example:

foreach (var package in this.chartJS31.Packages)
{
System.Diagnostics.Debug.WriteLine(package.Name + ": " + package.Source);
}

Methods​

Instance member GetImage(callback)​

Retrieves the chart as a PNG image and passes it to the callback method.

ParameterTypeDescription
callbackAction<Image>Callback method that receives the Image with a representation of the chart, or null if the image could not be retrieved.

The image is rendered by the client canvas and the callback is invoked when the client returns it. The chart is drawn over the BackColor of the control. Use GetImageAsync to await the image instead.

Throws:

Example:

this.chartJS31.GetImage(image =>
{
if (image != null)
image.Save(Application.MapPath("chart.png"), System.Drawing.Imaging.ImageFormat.Png);
});

Instance member GetImageAsync()​

Returns the chart as a PNG image.

Returns: Task<Image>. A task that completes with an Image with a representation of the chart, or null if the image could not be retrieved.

The image is rendered by the client canvas and sent back to the server asynchronously. The chart is drawn over the BackColor of the control. The result is null when the chart has not been rendered yet or the image data cannot be decoded.

Example:

private async void buttonSnapshot_Click(object sender, EventArgs e)
{
var image = await this.chartJS31.GetImageAsync();
if (image != null)
this.pictureBox1.Image = image;
}

Protected member OnChartClick(e)​

Fires the ChartClick event.

ParameterTypeDescription
eChartClickEventArgs

Protected member OnWebRender(config)​

Renders the client component.

ParameterTypeDescription
configObjectDynamic configuration object.

Protected member OnWidgetEvent(e)​

Handles events fired by the widget.

ParameterTypeDescription
eWidgetEventArgs

Instance member UpdateData(duration)​

Causes the chart to update the data sets and labels. It performs a smooth animated transition from one data set to the new one.

ParameterTypeDescription
duration optionalInt32Duration of the update animation in milliseconds, passed to the update call of the client chart. The default is 300 milliseconds.

Only the Data values of each data set and the Labels are updated on the client; other data set properties, including Formatted, are not updated. The data sets must correspond to the ones already displayed: to add or remove data sets, change DataSets, which redraws the chart. If the control is already scheduled for a full redraw, this method does nothing since the redraw includes the new data.

Example:

private void timer1_Tick(object sender, EventArgs e)
{
var random = new Random();
var data = this.chartJS31.DataSets[0].Data;
for (int i = 0; i < data.Length; i++)
data[i] = random.Next(100);

this.chartJS31.UpdateData(500);
}

Events​

Instance member ChartClick​

ChartClickEventHandler Fired when the user clicks a data point on the chart.

The event is fired only at runtime and only when the click hits at least one active chart element. The ChartClickEventArgs argument contains the data sets, the indexes of the data points and the values of the elements under the click point, in matching order.

Example:

public Page1()
{
InitializeComponent();
this.chartJS31.ChartClick += this.chartJS31_ChartClick;
}

private void chartJS31_ChartClick(object sender, ChartClickEventArgs e)
{
int point = e.DataPoints[0];
AlertBox.Show($"{e.DataSets[0].Label} - {this.chartJS31.Labels[point]}: {e.Values[0]}");
}

Implements​