如果图表数据为空,如何显示消息? [英] How to show a message if chart data is empty?

查看:226
本文介绍了如果图表数据为空,如何显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有图表和数据库的WinForm.图表从数据库中获取数据.如果没有数据,则看不到图表.我想在图表位置显示一条消息,例如:尚无数据".我可以吗?

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)
{
   ???
}

推荐答案

..在图表中显示一条消息..我可以吗?

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

好的.实际上,有很多方法,从设置图表的Title到使用Paint事件和DrawString或创建TextAnnotation等.

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.

示例1 -A TextAnnotation:

TextAnnotation ta = new TextAnnotation();

像这样设置它:

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);

在数据更改时显示:

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


示例2 -在Paint事件中绘制消息:


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);

    }
}

这应该保持自身更新,因为添加或删除DataPoints会触发Paint事件.

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

顺便说一句:使用Linq Any()函数,推荐方法来测试集合中是否包含任何数据:

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.

这篇关于如果图表数据为空,如何显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆