简体   繁体   中英

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#. 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:

在此处输入图片说明

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM