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