Skip to main content

ChartJS4

Namespace: Wisej.Web.Ext.ChartJS4

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

ChartJS4 is a modernized, flexible Chart.js 4.x integration for Wisej.NET. Features improved serialization, better maintainability, and easier customization.

public class ChartJS4 : Widget

The chart is configured on the server through ChartType, Labels, DataSets and ChartOptions. Changing any of these properties (or the content of the observable LabelCollection and DataSetCollection) schedules a refresh of the client-side chart.

Use UpdateData to update only the data and labels with an animation, and the client-call methods (e.g. GetImage, ToBase64Image, IsDatasetVisible) to invoke the corresponding Chart.js API on the client. Methods that return a value from the client are asynchronous and deliver the result to a callback.

Example:

var chart = new ChartJS4 { Dock = DockStyle.Fill, ChartType = ChartType.Bar };
chart.Labels = new[] { "Jan", "Feb", "Mar" };
chart.DataSets.Add(new BarDataSet { Label = "Sales", Data = new object[] { 10, 20, 15 } });
chart.ChartOptions.Plugins.Title.Display = true;
chart.ChartOptions.Plugins.Title.Text = "Quarterly Sales";
this.Controls.Add(chart);

Constructors​

Instance member ChartJS4()​

Constructs a new instance of the ChartJS4 control.

The new control has an empty Labels and DataSets collection bound to it and a ChartType of Line.

Example:

var chart = new ChartJS4 { Dock = DockStyle.Fill };
this.Controls.Add(chart);

Properties​

Instance member ChartOptions​

ChartOptions: Returns or sets the chart options (Chart.js options).

Value: A ChartOptions instance. The getter lazily creates a new instance when none is set.

Nested option objects (e.g. Plugins, Scales) are also created lazily on first access, so they can be configured directly. When rendered, the options are serialized to JSON and properties that match their default values, empty objects and null values are removed. Assigning the property refreshes the chart.

Example:

var chart = new ChartJS4();
chart.ChartOptions.Plugins.Legend.Position = "bottom";
chart.ChartOptions.Plugins.Title.Display = true;
chart.ChartOptions.Plugins.Title.Text = "Monthly Revenue";

Instance member ChartType​

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

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

The value is sent to Chart.js as the lower-case type of the chart configuration, unless Type is set, in which case that value takes precedence. Changing the value refreshes the chart.

Example:

var chart = new ChartJS4();
chart.ChartType = ChartType.Doughnut;

Instance member DataSets​

DataSetCollection: Returns or sets the data sets for the chart (Chart.js data.datasets).

Value: A DataSetCollection of ChartDataSet objects (e.g. LineDataSet, BarDataSet, PieDataSet). Assigning null replaces it with a new empty collection.

DataSetCollection supports implicit conversion from ChartDataSet[] and List<ChartDataSet>. Assigning the property, or adding, removing or replacing data sets, refreshes the chart. Use UpdateData to push data changes with an animation.

Example:

var chart = new ChartJS4();
chart.DataSets.Add(new LineDataSet
{
Label = "Visitors",
Data = new object[] { 12, 19, 3, 5 },
BorderColor = Color.SteelBlue
});

Instance member InitScript​

String: Returns the JavaScript initialization script of the chart widget.

Value: The content of the embedded startup.js resource, which creates the Chart.js instance on the client and implements the client-side methods invoked by this control.

The setter is ignored: the initialization script is always loaded from the embedded resource.

Example:

var script = chart.InitScript;
System.Diagnostics.Debug.WriteLine(script.Length);

Instance member Labels​

LabelCollection: Returns or sets the labels for the chart data (Chart.js data.labels).

Value: A LabelCollection. Assigning null replaces it with a new empty collection.

LabelCollection supports implicit conversion from string[] and List<string>. Assigning the property, or adding, removing or changing labels, refreshes the chart.

Example:

var chart = new ChartJS4();
chart.Labels = new[] { "Mon", "Tue", "Wed" };
chart.Labels.Add("Thu");

Instance member Options​

Object: Returns or sets the raw configuration object sent to the client widget.

Value: A dynamic object with the type, options, widgetFunctions and data fields passed to the Chart.js constructor.

This property is hidden from the designer. It is regenerated every time the control renders from ChartType, ChartOptions, WidgetFunctions, Labels and DataSets, so values assigned directly are overwritten. Use ChartOptions to configure the chart instead.

Example:

// Configure the chart through ChartOptions rather than Options.
chart.ChartOptions.Plugins.Legend.Position = "bottom";
chart.Update();

Instance member Packages​

List<Package>: Returns the list of script packages required by the chart.

Value: The list of Package objects loaded on the client before the chart widget is created.

The list is built on first access and contains, in order:

  1. The embedded Chart.js 4 library, chartjs-plugin-datalabels, the chartjs-adapter-date-fns bundle and moment.js.
  2. Every embedded resource found in a ChartJsPlugins folder of any loaded assembly (other than this one).
  3. The packages registered in PluginPackages.

Example:

foreach (var package in chart.Packages)
System.Diagnostics.Debug.WriteLine($"{package.Name}: {package.Source}");

Static member PluginPackages​

List<Package>: Returns the list of additional plugin packages to load with the chart. Use this to register custom Chart.js plugins globally (e.g., in Application_Start).

Value: A static, application-wide list of Package objects. Empty by default.

The packages are appended to Packages after the built-in scripts (Chart.js, chartjs-plugin-datalabels, the date-fns adapter and moment.js) and after the scripts discovered automatically from embedded resources placed in a ChartJsPlugins folder of any loaded assembly.

Because Packages is built the first time it is read, register plugin packages before the first chart is created.

Example:

ChartJS4.PluginPackages.Add(new Package
{
Name = "chartjs-plugin-zoom.js",
Source = "https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2/dist/chartjs-plugin-zoom.min.js"
});

Instance member WidgetFunctions​

WidgetFunction[]: Returns or sets the widget functions that are passed to the chart. Widget functions allow JavaScript callbacks (e.g., scriptable options) to be defined server-side and called client-side using the (ctx)=>functionName pattern.

Value: An array of WidgetFunction objects, or null (the default).

Any string option value in ChartOptions or DataSets matching (args)=>Name is replaced on the client by a function whose parameters are args and whose body is the Source of the function with the same Name. The form (args)=>Name(values) instead invokes the function once and assigns the returned value.

Each function is also registered on the client widget under its name.

Example:

chart.WidgetFunctions = new[]
{
new ChartJS4.WidgetFunction
{
Name = "barColor",
Source = "return ctx.raw > 10 ? 'green' : 'red';"
}
};
chart.DataSets.Add(new BarDataSet { Data = new object[] { 5, 15, 8 }, BackgroundColor = "(ctx)=>barColor" });

Methods​

Instance member Clear()​

Clears the chart canvas.

Invokes the Chart.js chart.clear() method on the client. The chart is drawn again on the next update or render.

Example:

chart.Clear();

Instance member Destroy()​

Destroys the chart instance, cleaning up any references and event listeners.

Invokes the Chart.js chart.destroy() method on the client. The control itself is not disposed; the chart is re-created the next time the control is refreshed (e.g. by calling Update()).

Example:

chart.Destroy();

Instance member GenerateLegend(callback)​

Generates an HTML legend for the chart.

ParameterTypeDescription
callbackAction<String>Callback that receives the HTML string, or an empty string if the chart is not available.

Invokes chart.generateLegend() on the client. Note that Chart.js 3 and later no longer provide this method natively; it works only when it has been added to the chart (for example by a plugin), otherwise the client call fails. For custom HTML legends in Chart.js 4 consider an HTML legend plugin.

Throws:

Example:

chart.GenerateLegend(html =>
{
this.htmlPanel1.Html = html;
});

Instance member GetActiveElements(callback)​

Retrieves the currently active (hovered) elements.

ParameterTypeDescription
callbackAction<Object[]>Callback that receives the array of active elements, or an empty array when there are none or the result could not be read.

Invokes the Chart.js chart.getActiveElements() method on the client. Each element is a dynamic object that typically exposes the datasetIndex and index fields.

Throws:

Example:

chart.GetActiveElements(elements =>
{
this.labelInfo.Text = $"{elements.Length} active element(s)";
});

Instance member GetDataVisibility(index, callback)​

Retrieves the visibility state of data at the specified index.

ParameterTypeDescription
indexInt32Index of the data.
callbackAction<Boolean>Callback that receives true if the data at index is visible; otherwise false.

Invokes the Chart.js chart.getDataVisibility(index) method on the client.

Throws:

Example:

chart.GetDataVisibility(2, isVisible =>
{
AlertBox.Show(isVisible ? "Visible" : "Hidden");
});

Instance member GetImage(callback)​

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

ParameterTypeDescription
callbackAction<Image>Callback method that receives the Image of the chart, rendered over the control's BackColor, or null if the client could not produce an image.

The image is produced asynchronously by the browser from the chart's canvas. See GetImageAsync for the awaitable version.

Throws:

Example:

chart.GetImage(image =>
{
if (image != null)
image.Save(Application.MapPath("chart.png"));
});

Instance member GetImageAsync()​

Asynchronously returns the chart as a PNG image.

Returns: Task<Image>. A task that completes with an Image of the chart rendered over the control's BackColor, or null if the client could not produce an image.

This is the awaitable version of GetImage. The image is produced by the browser from the chart's canvas.

Example:

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

Instance member GetVisibleDatasetCount(callback)​

Retrieves the number of visible datasets.

ParameterTypeDescription
callbackAction<Int32>Callback that receives the count of visible datasets.

Invokes the Chart.js chart.getVisibleDatasetCount() method on the client.

Throws:

Example:

chart.GetVisibleDatasetCount(count =>
{
this.labelInfo.Text = $"{count} of {chart.DataSets.Count} datasets visible";
});

Instance member Hide(datasetIndex)​

Hides a dataset and triggers the 'hide' animation.

ParameterTypeDescription
datasetIndexInt32Index of the dataset to hide.

Invokes the Chart.js chart.hide(datasetIndex) method on the client. The chart is updated automatically; no additional update call is needed.

Example:

chart.Hide(0);

Instance member Hide(datasetIndex, dataIndex)​

Hides a specific data element in a dataset and triggers the 'hide' animation.

ParameterTypeDescription
datasetIndexInt32Index of the dataset.
dataIndexInt32Index of the data element.

Invokes the Chart.js chart.hide(datasetIndex, dataIndex) method on the client.

Example:

// hide the third slice of a pie chart.
chart.Hide(0, 2);

Instance member IsDatasetVisible(datasetIndex, callback)​

Checks if a dataset is visible.

ParameterTypeDescription
datasetIndexInt32Index of the dataset.
callbackAction<Boolean>Callback that receives true if the dataset is visible; otherwise false.

Invokes the Chart.js chart.isDatasetVisible(datasetIndex) method on the client.

Throws:

Example:

chart.IsDatasetVisible(0, visible =>
{
chart.SetDatasetVisibility(0, !visible);
chart.UpdateChart();
});

Protected member OnChartClick(e)​

Fires the ChartClick event.

ParameterTypeDescription
eChartClickEventArgsEvent arguments.

Protected member OnWebRender(config)​

Renders the client component.

ParameterTypeDescription
configObject

Protected member OnWidgetEvent(e)​

Handles events fired by the widget.

ParameterTypeDescription
eWidgetEventArgs

Instance member Render()​

Triggers a redraw of all chart elements.

Invokes the Chart.js chart.render() method on the client. Unlike UpdateChart, it does not update elements with new data; use it to redraw after changes that don't affect the data.

Example:

chart.Render();

Instance member Reset()​

Resets the chart to its state before the initial animation.

Invokes the Chart.js chart.reset() method on the client. A subsequent UpdateChart call runs the initial animation again.

Example:

chart.Reset();
chart.UpdateChart();

Instance member ResetChartType()​

Resets the ChartType property to its default value (Line).

Used by the designer. This method assigns the backing field directly and does not refresh the chart.

Example:

chart.ResetChartType();

Instance member Resize(width, height)​

Resizes the chart canvas. If no dimensions are provided, detects the new size from the container.

ParameterTypeDescription
width optionalNullable<Int32>Optional width in pixels.
height optionalNullable<Int32>Optional height in pixels.

Invokes the Chart.js chart.resize() method on the client. Both width and height must be specified to set an explicit size; if either is omitted the size is detected from the container.

Example:

chart.Resize();
chart.Resize(640, 480);

Instance member SetActiveElements(activeElements)​

Sets the active (hovered) elements for the chart.

ParameterTypeDescription
activeElementsObject[]Array of active element specifications. Each item is an object with the datasetIndex and index fields. An empty array clears the active elements.

Invokes the Chart.js chart.setActiveElements() method on the client. This sets the hover state of the elements; to also show the tooltip use the Chart.js tooltip API on the client.

Example:

chart.SetActiveElements(new object[]
{
new { datasetIndex = 0, index = 1 },
new { datasetIndex = 1, index = 1 }
});

Instance member SetDatasetVisibility(datasetIndex, visible)​

Sets the visibility of a dataset.

ParameterTypeDescription
datasetIndexInt32Index of the dataset.
visibleBooleantrue to show, false to hide.

Invokes the Chart.js chart.setDatasetVisibility(datasetIndex, visible) method on the client. The change is not drawn until the chart is updated, e.g. with UpdateChart.

Example:

chart.SetDatasetVisibility(1, false);
chart.UpdateChart();

Instance member ShouldSerializeChartType()​

Determines whether the ChartType property should be serialized by the designer.

Returns: Boolean. true if ChartType differs from Line; otherwise false.

Used by the designer and the code serializer.

Example:

if (chart.ShouldSerializeChartType())
chart.ResetChartType();

Instance member Show(datasetIndex)​

Shows a dataset and triggers the 'show' animation.

ParameterTypeDescription
datasetIndexInt32Index of the dataset to show.

Invokes the Chart.js chart.show(datasetIndex) method on the client. The chart is updated automatically; no additional update call is needed.

Example:

chart.Show(0);

Instance member Show(datasetIndex, dataIndex)​

Shows a specific data element in a dataset and triggers the 'show' animation.

ParameterTypeDescription
datasetIndexInt32Index of the dataset.
dataIndexInt32Index of the data element.

Invokes the Chart.js chart.show(datasetIndex, dataIndex) method on the client.

Example:

chart.Show(0, 2);

Instance member Stop()​

Stops all currently running animations on the chart.

Invokes the Chart.js chart.stop() method on the client.

Example:

chart.Stop();

Instance member ToBase64Image(type, quality, callback)​

Returns a base64 encoded string of the chart in the requested format.

ParameterTypeDescription
typeStringImage MIME type (e.g., "image/png", "image/jpeg", "image/webp").
qualityDoubleQuality for lossy formats (0.0 to 1.0).
callbackAction<String>Callback that receives the image as a data URL (data:<type>;base64,…), or an empty string if the chart is not available.

Invokes the Chart.js chart.toBase64Image(type, quality) method on the client.

Throws:

Example:

chart.ToBase64Image("image/jpeg", 0.8, dataUrl =>
{
this.pictureBox1.ImageSource = dataUrl;
});

Instance member ToBase64Image(callback)​

Returns a base64 encoded string of the chart in PNG format.

ParameterTypeDescription
callbackAction<String>Callback that receives the PNG image as a data URL (data:image/png;base64,…), or an empty string if the chart is not available.

Equivalent to calling ToBase64Image with "image/png" and a quality of 1.0.

Throws:

Example:

chart.ToBase64Image(dataUrl =>
{
this.pictureBox1.ImageSource = dataUrl;
});

Instance member ToggleDataVisibility(index)​

Toggles the visibility of data at the specified index across all datasets.

ParameterTypeDescription
indexInt32Index of the data.

Invokes the Chart.js chart.toggleDataVisibility(index) method on the client. This is mostly useful for charts where each data item has its own legend entry, such as pie, doughnut and polar area charts. The change is not drawn until the chart is updated, e.g. with UpdateChart.

Example:

chart.ToggleDataVisibility(2);
chart.UpdateChart();

Instance member UpdateChart(mode)​

Triggers an update of the chart. This will update all scales, legends, and re-render the chart.

ParameterTypeDescription
mode optionalStringThe update mode. Can be "none", "resize", "reset", "hide", "show", "normal" or "active". When null or empty, the default Chart.js update is performed.

Invokes the Chart.js chart.update(mode) method on the client. Use "none" to update without animation.

Example:

chart.UpdateChart();
chart.UpdateChart("none");

Instance member UpdateData(duration)​

Causes the chart to update the data set and labels with animation.

ParameterTypeDescription
duration optionalInt32Duration of the update animation in milliseconds. The default is 300.

Sends the current DataSets and Labels to the client and updates the existing Chart.js data in place, allowing smooth transitions. The call is skipped when the control is already scheduled for a full refresh.

Example:

chart.DataSets[0].Data = new object[] { 5, 8, 13, 21 };
chart.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 chart element. Data contains a data array with one entry per element under the pointer, each with the pointIndex and dataSetIndex fields.

Example:

chart.ChartClick += (s, e) =>
{
var point = e.Data.data[0];
AlertBox.Show($"DataSet {point.dataSetIndex}, point {point.pointIndex}");
};

Implements​