简体   繁体   中英

Getting points from a .txt file and plotting them in a picturebox in C#

I'm trying to build a windows form application in which I read a comma separated list from a .txt file and then plot that using the DrawLine function. My code keeps getting stuck in an infinite loop and I'm not sure how I should proceed further. I have no preference of how I should plot it and the only reason I'm using the drawline function is because I don't know of any other way so I'm open to any other ideas that might be better suited to doing this task.

       private void startToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader("../../sample.txt");
        string[] values = null;
        zee1 = sr.ReadLine();
        while (zee1 != null)
        {
            values = zee1.Split(',');
            x1 = Int32.Parse(values[0]);
            x2 = Int32.Parse(values[1]);
            y1 = Int32.Parse(values[2]);
        }



        //BackGroundBitmap.Save("result.jpg"); //test if ok
        Point point1 = new Point(int.Parse(values[0]), int.Parse(values[2]));
        Point point2 = new Point(int.Parse(values[1]), int.Parse(values[2]));

        pictureBox1.Enabled = true;
        g = pictureBox1.CreateGraphics();
        g.DrawLine(pen1, point1, point2);
    }

Please note I'm trying to plot two different values of x on the same plot for the same values of y. Also that values[0] is an array that contains all the data in the first column of the .txt file and so forth for values[1] and values[2].

The txt file I'm using is as follows

0,4,0

1,2,1

2,1,2

3,6,3

4,1,4

5,3,5

6,8,6

You're in an infinite while loop because the condition never changes. You need to update zee1 . The most popular way to do this is to simply update it in the condition:

while ((zee1 = sr.ReadLine()) != null)
{
    // what was here already
}

It also seems as if you want to draw a set of line segments (I assume one to the next), so you could do that like so:

private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
    List<Point> points = new List<Point>();
    using (StreamReader sr = new StreamReader("../../sample.txt"))
    {
        string[] values = null;
        while ((zee1 = sr.ReadLine()) != null)
        {
            values = zee1.Split(',');
            points.Add(new Point(int.Parse(values[0]), int.Parse(values[2])));
        }
    }

    pictureBox1.Enabled = true;
    g = pictureBox1.CreateGraphics();
    for (int i = 0; i < points.Count - 1; i++)
        g.DrawLine(pen1, points[i], points[i+1]);
}

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