Can I display a message if MS Chart Control has no data?

人盡茶涼 提交于 2019-12-09 15:17:51

问题


Is there a way to display a "default" message on a MS Chart Control if there is no data to chart?

I have a chart, with some controls that allow the user to pick various date ranges. If there is no data to be charted in that date range, it currently just displays nothing (or at least it shows the legend, and background, but that's it.)

I want there to be a message saying "no data for this period" or something instead.

Thanks,

Ben


回答1:


Building on Chris's response, here's a more complete example:

In the ASPX code, add the OnDataBound handler to the chart tag. This assumes you are using a SqlDataSource for the data source.

<asp:Chart ID="ChartExample" runat="server" 
    DataSourceID="SqlDataSourceExample" 
    OnDataBound="ChartExample_DataBound">

In the code-behind, the handler checks if the first series has any data, and if it doesn't, inserts the annotation in red.

protected void ChartExample_DataBound(object sender, EventArgs e)
{
    // If there is no data in the series, show a text annotation
    if(ChartExample.Series[0].Points.Count == 0)
    {
        System.Web.UI.DataVisualization.Charting.TextAnnotation annotation = 
            new System.Web.UI.DataVisualization.Charting.TextAnnotation();
        annotation.Text = "No data for this period";
        annotation.X = 5;
        annotation.Y = 5;
        annotation.Font = new System.Drawing.Font("Arial", 12);
        annotation.ForeColor = System.Drawing.Color.Red;
        ChartExample.Annotations.Add(annotation);
    }
}



回答2:


You should be able to add an annotation to the chart if there is no data.

TextAnnotation annotation = new TextAnnotation();
annotation.X = 50;
annotation.Y = 50;
annotation.Text = "No Data";
chart1.Annotations.Add(annotation);



回答3:


I guess that you cast retrieved data to an Array and use it for chart binding, if so
you can use a label, show/hide it according array length, as there is no property to be displayed a certain text if chart has no data.

    if (arr.Length > 0)
    {
        lblEmptyMSG.Visible = false;
    }
    else
    {
        lblEmptyMSG.Visible = true;
    }


来源:https://stackoverflow.com/questions/4452841/can-i-display-a-message-if-ms-chart-control-has-no-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!