How to make ASP.NET chart's X-axis label clickable and trigger a function?
The ASP.NET Chart renders an image (png by default) using the html img tag as follows:
<img id="Chart1"
src="/ChartImg.axd?i=chart_0_0.png&g=6d177535e0d24eb8b9a60872279889e8"
alt=""
style="height:300px;width:600px;border-width:0px;" />
Although the image itself is not interactive you will probably be able to make the chart interactive. See the following Chart sample provided by Microsoft:
The source code shown in the "C# Source" tab is as follows:
/// <summary>
/// Page Load event handler.
/// </summary>
protected void Page_Load(object sender, System.EventArgs e)
{
this.Chart1.Click += new ImageMapEventHandler(Chart1_Click);
// direct using of PostBackValue
foreach (Series series in this.Chart1.Series)
{
series.PostBackValue = "series:" + series.Name + ",#INDEX";
}
// transfer of click coordinates. getCoordinates is a javascript function.
string postbackScript = ClientScript.GetPostBackEventReference(this.Chart1, "chart:@");
this.Chart1.Attributes["onclick"] = postbackScript.Replace("@'", "' + getCoordinates(event)");
}
/// <summary>
/// Handles the Click event of the Chart1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.ImageMapEventArgs"/> instance containing the event data.</param>
protected void Chart1_Click(object sender, ImageMapEventArgs e)
{
this.Chart1.Titles["ClickedElement"].Text = "Nothing";
string[] input = e.PostBackValue.Split(':');
if (input.Length == 2)
{
string[] seriesData = input[1].Split(',');
if (input[0].Equals("series"))
{
this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element: " + seriesData[0] + " - Data Point #" + seriesData[1];
}
else if (input[0].Equals("chart"))
{
// hit test of X and Y click point
HitTestResult hitTestResult = this.Chart1.HitTest(Int32.Parse(seriesData[0]), Int32.Parse(seriesData[1]));
if (hitTestResult != null)
{
this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element: " + hitTestResult.ChartElementType.ToString();
}
}
}
}