How to show a message if chart data is empty?

橙三吉。 提交于 2019-12-24 14:27:51

问题


I have WinForm with chart and database.Chart get data from database. If no data the chart isn't visible. I would like to show a message in the chart place.For example: "No data yet." Can I do it?

if (chart1["Series1"].Points.Count == 0)
{
   ???
}

回答1:


..show a message in the chart..Can I do it?

Sure. There are in fact many ways, from setting the chart's Title to using the Paint event and DrawString or creating a TextAnnotation etc..

The two latter options are easy to center and both will keep the position even when the chart is resized.

Example 1 - A TextAnnotation:

TextAnnotation ta = new TextAnnotation();

Set it up like this:

ta.Text = "No Data Yet";
ta.X = 45;  // % of the..
ta.Y = 45;  // chart size 
ta.Font = new Font("Consolas", 20f);
ta.Visible = false;  // first we hide it
chart1.Annotations.Add(ta);

Show whenever the data are changed:

ta.Visible = (chart1.Series[seriesNameOrIndex].Points.Count == 0)

Example 2 - Drawing the messag in the Paint event:

private void chart1_Paint(object sender, PaintEventArgs e)
{
    if (chart1.Series[seriesNameOrIndex].Points.Count == 0)
    {
        using (Font font = new Font("Consolas", 20f))
        using (StringFormat fmt = new StringFormat()
        { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })

            e.Graphics.DrawString("No data yet", 
                                  font, Brushes.Black, chart1.ClientRectangle, fmt);

    }
}

This should keep itself updated as adding or removing DataPoints will trigger the Paint event.

Btw: The recommended way to test to a collection to contain any data is using the Linq Any() function:

(!chart1.Series[seriesNameOrIndex].Points.Any())

It is both as fast as possible and clear in its intent.



来源:https://stackoverflow.com/questions/55621622/how-to-show-a-message-if-chart-data-is-empty

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