[英]Display all points in chart control on a windows form in C#
I am trying to display several points with x and y coordinates between 0 and 200 in a chart control on a Windows form app in C#. 我试图在C#的Windows窗体应用程序的图表控件中显示0和200之间的x和y坐标的几个点。 My code looks like the following:
我的代码如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public class Point
{
public double X;
public double Y;
public Point(double x, double y)
{
X = x;
Y = y;
}
}
public Form1()
{
InitializeComponent();
List<Point> points = new List<Point>();
for (int i=0; i<5; i++)
{
points.Add(new Point(GetRandomNumber(0, 200), GetRandomNumber(0, 200)));
}
foreach(Point f in points)
{
chart1.Series["Series1"].Points.AddXY(f.X, f.Y);
}
Application.DoEvents();
}
double GetRandomNumber(double minimum, double maximum)
{
Random random = new Random();
return random.NextDouble() * (maximum - minimum) + minimum;
}
}
}
When I run this, however, I get this plot: 但是,当我运行它时,我得到以下图:
I get a similar result no matter what range I use. 无论使用什么范围,我都会得到类似的结果。 For example, the following output is for x and y in the range of 0, 30:
例如,以下输出是x和y的范围为0、30的输出:
However, when I manually enter some random points to the list, the chart scales appropriately, and they all show up o it just fine: 但是,当我手动向列表中输入一些随机点时,图表会适当缩放,并且它们都会很好地显示出来:
List<Point> points = new List<Point>
{
new Point(10, 29),
new Point(5, 16),
new Point(27, 8),
new Point(17, 23),
new Point(22, 13)
};
Why is this? 为什么是这样? and how can I get all points to display appropriately, when randomly generated.
以及在随机生成时如何使所有点正确显示。
I am using: 我在用:
Microsoft Visual Studio Community 2017
Visual C# 2017 00369-60000-00001-AA613
Microsoft Visual C# 2017
Answering My own question with the help of @HansPassant. 在@HansPassant的帮助下回答我自己的问题。 Apparently, because I was creating a new random object every time, the random number generator was generating the same number every time, and all the points were on top of each other.
显然,因为我每次都创建一个新的随机对象,所以随机数生成器每次都生成相同的数字,并且所有的点都在彼此之上。 I fixed it by declaring a 'random' object in the constructor and then passing it into my 'GetRandomNumber' function.
我通过在构造函数中声明一个“随机”对象,然后将其传递给我的“ GetRandomNumber”函数来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.