generate plot from populated DataGridView
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: generate plot from populated DataGridView

  1. #1
    Join Date
    May 2011
    Posts
    12

    generate plot from populated DataGridView

    I would like to try plotting x and multiple y data from data residing in DataGridView. I populate datagridview but have no idea how to handle an event to get it plotted. I am using windows forms. I am trying to plot via OnPaint but there is no plot. Here is the relevant part:

    protected override void OnPaint(PaintEventArgs e)
    {

    ds = new DataSeries();
    ds.LineStyle.LineColor = Color.Red;
    ds.LineStyle.Thickness = 2f;
    ds.LineStyle.Pattern = DashStyle.Dash;
    ds.SeriesName = "sine";
    for (int i = 0; i < dataGridView1.RowCount; i++)
    {
    string value1 = dataGridView1[0, i].Value as string;
    string value2 = dataGridView1[1, i].Value as string;
    if (value1 != null && value2 != null)
    {
    float x = Convert.ToSingle(
    (string)dataGridView1[0, i].Value);
    float y = Convert.ToSingle(
    (string)dataGridView1[1, i].Value);
    ds.AddPoint(new PointF(x, y));
    }
    }
    //e.Graphics.DrawLines(Pen, PointF(x,y));
    base.OnPaint(e);
    }

    and DataSet:

    namespace Example8_3
    {
    public class DataSeries
    {
    private ArrayList pointList;
    private LineStyle lineStyle;
    private string seriesName = "Default Name";

    public DataSeries()
    {
    lineStyle=new LineStyle();
    pointList=new ArrayList();
    }

    public LineStyle LineStyle
    {
    get { return lineStyle; }
    set { lineStyle = value; }
    }

    public string SeriesName
    {
    get { return seriesName; }
    set { seriesName = value; }
    }

    public ArrayList PointList
    {
    get { return pointList; }
    set { pointList = value; }
    }

    public void AddPoint(PointF pt)
    {
    pointList.Add(pt);
    }
    }
    }

  2. #2
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    I meant DataSeries:

    //e.Graphics.DrawLines(Pen, PointF(x,y));
    base.OnPaint(e);
    }

    and DataSeries:

    namespace Example8_3
    {
    public class DataSeries
    {

  3. #3
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    OK, simplified everything. How would I use OnPaint and DrawLine to plot data from DataGridView? The code below gives me exception that

    float x2 = Convert.ToSingle(
    (string)dataGridView1[0, (i+1)].Value);
    float y2 = Convert.ToSingle(
    (string)dataGridView1[1, (i+1)].Value);

    is wrong but I can;t find out what's wrong

    protected override void OnPaint(PaintEventArgs e)
    {
    Graphics g = e.Graphics;
    for (int i = 0; i < dataGridView1.RowCount; i++)
    {

    float x1 = Convert.ToSingle(
    (string)dataGridView1[0, i].Value);
    float y1 = Convert.ToSingle(
    (string)dataGridView1[1, i].Value);
    float x2 = Convert.ToSingle(
    (string)dataGridView1[0, (i+1)].Value);
    float y2 = Convert.ToSingle(
    (string)dataGridView1[1, (i+1)].Value);

    g.DrawLine(Pens.Blue, x1, y1, x2, y2);

    }

    }

  4. #4
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: generate plot from populated DataGridView

    You will need to narrow down what the exception is... can you provide the exception text, then we could probably tell you what is causing that exception... thanks

  5. #5
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    sure. I am getting:

    Input string was not in a correct format.

    All I want to do is to import data set into datagridview (which I do successfully) and then plot it connecting points with lines

  6. #6
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: generate plot from populated DataGridView

    Have you stepped through the routine to see what the value of each cell was as you attempt to cast it the value to float? It seems to be having trouble with the casting, but since I can't see what is in each datagrid cell, it's hard to tell which line is throwing that at you and why.

    I created a small test of your issue, and this onPaint method is working for me... there are little things I'm not handling such as new rows that are auto-created in the grid as I enter values, etc... but... it draws the lines from point to point as I add values to the grid without exceptions being throw. Hope this helps...

    (Note: paintEmpty() is just a method I created so the panel woudl say "Invalid Data" if less than two rows existed...)

    Code:
            private void onPaintPanel(object sender, PaintEventArgs e)
            {
                Graphics g = e.Graphics;
    
                if (this.dataGridView1.Rows.Count < 2)
                    paintEmpty(g);
                else
                {
                    g.Clear(Color.White);
    
                    foreach (DataGridViewRow row in this.dataGridView1.Rows)
                    {
                        if ((row.Index + 1) < this.dataGridView1.Rows.Count)
                        {
                            // this point
                            float x1 = Convert.ToSingle(row.Cells[0].Value);
                            float y1 = Convert.ToSingle(row.Cells[1].Value);
                            // next point
                            float x2 = Convert.ToSingle(this.dataGridView1.Rows[row.Index + 1].Cells[0].Value);
                            float y2 = Convert.ToSingle(this.dataGridView1.Rows[row.Index + 1].Cells[1].Value);
    
                            // dont plot backwards...
                            if (x2 >= x1)
                                g.DrawLine(Pens.Blue, new PointF(x1, y1), new PointF(x2, y2));
                        }
                    }
                }
            }

  7. #7
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    Much better. Now there is no exception.

    One question is: how do I step through routine?
    The other, bigger problem is: there is still no draing generated. I created windows forms window with two containers: one datagridview and the other one is chart. Where is the missing connection? I am doing data binding, e.g. I have a script to import values into datagridview table but how do I draw it? What's the trigger or event?

    thanks

  8. #8
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: generate plot from populated DataGridView

    Hmm, well, sounds like you are having a basic problem with understanding exactly what you are working with as far as controls and how they utilize information.

    Okay, first, to step through, you simply put a break-point on a line in your code where you want to start following along, then run your program in debug (F5), when the code executing hits a line with a break-point, it will stop there and hilight that line in yellow. While the code is stopped, you can hover over variables to see values, or use the immediate window to query objects or execute one-off lines of code to test things. Use [F10] to step line-by-line from that point... there are other F keys to step over, step into, etc... but you'll just need to study debugging in your IDE.

    Finally... if you are trying to use a chart control to plot this data... you are quite a ways off base attempting to do any drawing... after all, that is what the chart control was created to handle. The chart control will have a way to feed it the data points, and it will take care of drawing everything in the format you choose in that control.

    Not sure why you're bringing the data into a datagridview before charting it... maybe it's just a requirement of what you're doing... but at any rate, what you want to do is study the chart control that you are using, and find out how to feed it your data points... you shouldn't be concerned with onPaint methods at all for this... (unless you are creating your own chart control, of course...)

  9. #9
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    then this is exactly what I am going to do: study chart control. I'll come back and complain here (which I do very well) if I fail again
    any useful link for chart control?
    Last edited by jbaltrus; May 28th, 2011 at 12:41 PM.

  10. #10
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: generate plot from populated DataGridView

    You can try this... (if you're using Microsoft Chart Control...)

    It looks like it's in VB... but it should give you the general idea of what you're looking to do... you want to fill the chart's "series" with data, and let the chart control handle displaying the chart according to that data.

    http://www.youtube.com/watch?v=bRnUAwUFIgY

  11. #11
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    not much luck. I have tab separated x-y text file and I need to plot it. I do not know how to feed that file into chart control

  12. #12
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: generate plot from populated DataGridView

    You don't feed the file, you feed the data... you need to...

    1. Get the data from the text file.

    2. Store it in a format needed by the chart control.

    3. Feed the data to the chart control (usually by setting ChartData, or adding values to a Series, etc...)

    If you need help with the individual steps, or having errors reading a file, not sure how to store the values in a list or array, etc etc... you can ask and you will probably get more help on those specific types of issues. It's hard for people to help when it is just sort of a wide open project and we don't know what the requirements are, what type of chart control you are using, etc.

  13. #13
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    OK, #1 and #2:

    I created a dataset

    public class Text2DataSet
    {
    public static DataSet Convert2DataSet(string tableName)
    {
    DataSet ds = new DataSet();

    ..............................

    ds.Tables[tableName].Rows.Add(items);

    Now my question is how about #3? How do I feed this data into Chart Control? Something like

    chart1.Series["Series1"].Points.AddY(yValue);

    this part startled me from the very beginning, e.g. I have event handler

    private void buttonAddPoints_Click(object sender, System.EventArgs e)
    {
    AddPoints();
    chart1.Invalidate();
    }

    how do I create a method to plot that dataset?

    thanks

  14. #14
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: generate plot from populated DataGridView

    Okay... well, if you have your points (x,y values) from the text file stored... you are merely wanting to set the chart series' data points to those values for your line chart so the control will render it for you. This is a little test I threw together and it seems to work fine... there is probably a better way to get it done, but just to give you something that appears to do what you are describing.

    Code:
            void PopulateChart()
            {
                DataTable dtData = new DataTable();
    
                dtData.Columns.Add("x", Type.GetType("System.Double"));
                dtData.Columns.Add("y", Type.GetType("System.Double"));
    
                for (double x = 10; x < 101; x += 10)
                {
                    double y = (double)new Random().Next(100);
                    dtData.Rows.Add(x,y);
                }
    
                this.chart1.Series[0].Points.Clear();
    
                foreach (DataRow dr in dtData.Rows)
                {
                    System.Windows.Forms.DataVisualization.Charting.DataPoint dp = new System.Windows.Forms.DataVisualization.Charting.DataPoint((double)dr[0], (double)dr[1]);
                    this.chart1.Series[0].Points.Add(dp);
                }
    
            }

  15. #15
    Join Date
    May 2011
    Posts
    12

    Re: generate plot from populated DataGridView

    Right, very useful. So I am trying to read an external data file filled with numbers into a DataTable. It all ends up quite ugly.

    First, I can't add the data as x and y (or possibly many y values)
    Second, I have problems then constructing datapoint as I am reading data as string via Streamreader
    Finally, can;t convert from string format into double
    And then probably more problems which I can;t even see

    Could you please a couple of tips?

    void PopulateChart()
    {
    DataTable dtData = new DataTable();

    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter="Text files (CRYSTAL'09 DOSS files|*.DOSS|All files (*.*)|*.*";
    openFileDialog1.FilterIndex=1;
    openFileDialog1.RestoreDirectory=true;

    if (openFileDialog1.ShowDialog()==DialogResult.OK)
    {
    StreamReader sr=new StreamReader(
    openFileDialog1.FileName);


    char[] cSplitter = { ' ', ',', ':', '\t'};

    //split the first line into the columns
    string[] columns=sr.ReadLine().Split(cSplitter);

    foreach (string col in columns)
    {
    dtData.Columns.Add(col);
    }

    //Read the rest of the data in the file
    string AllData=sr.ReadToEnd();
    string[] rows = AllData.Split("\r".ToCharArray());

    //Add data to the DataTable
    foreach (string row in rows)
    {
    string[] items = row.Replace("\r", "").Replace(" ", " ").Trim().Split(cSplitter);

    dtData.Rows.Add(items);

    }


    this.chart1.Series[0].Points.Clear();

    foreach (DataPoint dr in dtData.Rows)
    {
    DataPoint dp = new DataPoint((double)dr[0], (double)dr[1]);
    this.chart1.Series[0].Points.Add(dp);
    }


    }

    }

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center