Jump to content

cross thread operation not valid: control panel1 accessed from a thread other than th

- - - - -

  • Please log in to reply
1 reply to this topic

#1
tusyukomi

tusyukomi

    Newbie

  • Members
  • Pip
  • 3 posts
hi guys i have the following errors : cross thread operation not valid: control panel1 accessed from a thread other than the thread it was created on

i've tried searching the forum and they told me the error is refering to threading but i did not use threading in my codes.. my codes are shown below :

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZedGraph;
using System.IO.Ports;
using System.Diagnostics;


namespace ZedGraphSample
{
    public partial class Form1 : Form
    {
        int counter = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CreateGraph(zg1);
            SetSize();
        }

        private void CreateGraph(ZedGraphControl zgc)
        {
            GraphPane myPane = zgc.GraphPane;

            // Set the titles and axis labels
            myPane.Title.Text = "Waspmote Accelerometer Linegraph";
            myPane.XAxis.Title.Text = "Time/Secs";
            myPane.YAxis.Title.Text = "Acceleroemter Value";

            myPane.XAxis.Scale.Min = -0.5;
            myPane.XAxis.Scale.Max = 10.5;
            myPane.XAxis.Scale.MinorStep = 1;
            myPane.XAxis.Scale.MajorStep = 1;
            myPane.YAxis.Scale.Min = -3100;
            myPane.YAxis.Scale.Max = 3100;
            myPane.XAxis.Scale.MinorStep = 50;
            myPane.YAxis.Scale.MajorStep = 500;

            myPane.XAxis.Scale.MaxGrace = 1.0;

            myPane.AddCurve("X Axis", null, Color.Blue, SymbolType.Circle);
            myPane.AddCurve("Y Axis", null, Color.Red, SymbolType.Diamond);
            myPane.AddCurve("Z Axis", null, Color.Green, SymbolType.Square);
            zgc.AxisChange();
            clearGraph();
        }

        private void SetSize()
        {
            /*
            zg1.Location = new Point( 10, 10 );
            // Leave a small margin around the outside of the control
            zg1.Size = new Size( this.ClientRectangle.Width - 20, this.ClientRectangle.Height - 20 );

            GraphPane myPane = zg1.GraphPane;
            zg1.Size = new Size(myPane.CurveList[0].Points.Count * 50, this.ClientRectangle.Height - 20);
            */
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    clearGraph();
        //}

        private void clearGraph()
        {
            GraphPane myPane = zg1.GraphPane;
            myPane.CurveList[0].Clear();
            myPane.CurveList[1].Clear();
            myPane.CurveList[2].Clear();
            panel1.Refresh();
        }

        //private void button4_Click(object sender, EventArgs e)
        //{

        //    if (counter == 11)
        //    {
        //        clearGraph();
        //        counter = 0;
        //    }
        //    counter++;

        //    GraphPane myPane = zg1.GraphPane;
        //    Random rmd = new Random();

        //    for (int i = 0; i < 3; i++)
        //    {
        //        double y = rmd.NextDouble() * 3000;
        //        int a = rmd.Next(0, 2);

        //        //Random neg or pos value
        //        if (a == 1)
        //        {
        //            y *= -1.0;
        //        }
        //        PointPair point = new PointPair(counter - 1, y);


        //        myPane.CurveList[i].AddPoint(point);
        //    }

        //    // Calculate the Axis Scale Ranges
        //    zg1.AxisChange();
        //    panel1.Refresh();
        //}

        private void addPostion(double y, int index)
        {
            GraphPane myPane = zg1.GraphPane;
            PointPair point = new PointPair(counter - 1, y);
            myPane.CurveList[index].AddPoint(point);
            zg1.AxisChange();
            panel1.Refresh();
        }


        SerialPort serialPort = new SerialPort();
        string OutputToShow = "";
        List<byte> BufferByte = new List<byte>();
        bool GotHeaderBefore = false;

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
                serialPort.Close();
            try
            {
                {
                    //To set all the parameters for Serial Comm
                    serialPort.PortName = "COM4";
                    serialPort.BaudRate = int.Parse("38400");
                    serialPort.Parity = Parity.None;
                    serialPort.DataBits = 8;
                    serialPort.StopBits = StopBits.One;
                    serialPort.Encoding = System.Text.Encoding.ASCII;

                    //add event handler
                    serialPort.DataReceived += new SerialDataReceivedEventHandler(GotRawData);
                }

                //Open the selected Com Port
                serialPort.Open();

                //To show that Com Port is Opened
                //txtboxOutput.AppendText(DateTime.Now.ToString("hh:mm:ss tt") + " - COM14 is opened." + Environment.NewLine);
                //txtboxOutput.ScrollToEnd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }
        void GotRawData(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] DataInBytes = new byte[serialPort.BytesToRead];
            serialPort.Read(DataInBytes, 0, DataInBytes.Length);

            Debug.WriteLine(DataInBytes[0]);
            // If equals to '7E' (our header)
            if ((DataInBytes.Length > 0) && (DataInBytes[0] != 126))
            {
                if (GotHeaderBefore == true)
                {
                    // Extract buffer stuff
                    byte[] FinalBytes = BufferByte.ToArray();

                    // Split data between commas
                    string[] OutputArray = System.Text.ASCIIEncoding.ASCII.GetString(FinalBytes).Split(',');

                    // Do the DeeBee magic, baby!
                    if (OutputArray.Length > 3)
                    {
                        if (counter == 11)
                        {
                            clearGraph();
                            counter = 0;
                        }
                        counter++;

                        // Do DAL
                        TalkToDB(OutputArray);

                        //The act of printing on-screen
                        myDelegate z = new myDelegate(PrintData);
                        // txtboxOutput.Dispatcher.Invoke(z, new object[] { });
                    }

                    // Clear buffer
                    OutputArray = null;
                    BufferByte.Clear();
                    BufferByte = new List<byte>();
                }

                GotHeaderBefore = true;
            }

            // Add to buffer
            foreach (byte ByteMe in DataInBytes)
            {
                BufferByte.Add(ByteMe);
            }

        }

        void TalkToDB(string[] OutputArray)
        {
            // Cleanup the array elements
            int StartPosition = 0;
            char[] FindStart = OutputArray[0].ToCharArray();

            // Settle the 'common' packet details
            DateTime DateTimeChecked = DateTime.Now;
            string PanID = OutputArray[1].ToString();
            string MacAddress = OutputArray[2].ToString();

            // INSERT all sensor readings
            for (int q = 2; q < 6; q++)
            {
                string SensorType = OutputArray[q].Split('=')[0];
                decimal SensorValue = decimal.Parse(OutputArray[q].Split('=')[1]);
                OutputToShow = OutputToShow + SensorType + "=" + SensorValue + ", ";

                addPostion((float)SensorValue, q-2);
            }
            OutputToShow = OutputToShow + Environment.NewLine;
            Debug.WriteLine(OutputToShow);

        }

        // declare some variable needed
        delegate void SetTextDeleg(string TextAlignment);
        delegate void myDelegate();
        private void PrintData()
        {
            //txtboxOutput.AppendText(OutputToShow);
            // txtboxOutput.ScrollToEnd();
            OutputToShow = "";
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort.Close();
                // txtboxOutput.AppendText(DateTime.Now.ToString("hh:mm:ss tt") + "- COM14 is Closed." + Environment.NewLine);
                // txtboxOutput.ScrollToEnd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }


    }

}




can anybody provide help on this error ? thanks !

Edited by WingedPanther, 23 November 2011 - 07:00 AM.
add code tags (the # button)


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
Where, exactly, is the error occurring? That would make it a lot easier to find the issue.

Also, I added code tags for you (the # button) so we can read it :)
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users