How to fix "An object reference is required for the non-static field . . . " error?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mrcw
    New Member
    • Nov 2008
    • 82

    How to fix "An object reference is required for the non-static field . . . " error?

    Hi
    I've added a textbox called tbAccel0 to a form. It shows up on the form with the correct name, but when I look at the code a red squigly line appears under tbAccel0 and an error appears in the error list saying

    An object reference is required for the non-static field, method, or property

    I don't understand why. Surely an object reference was added when I added the textbox to the form.

    This is the only time this has happened, if a put a textbox on a new form it works normally as it should.



    this is the code. I have taken a working program and added an accelerometer to it (sorry it's so long)
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;
    
    using AForge;
    using AForge.Imaging;
    using AForge.Imaging.Filters;
    using AForge.Video;
    using AForge.Video.DirectShow;
    
    using Phidgets;
    using Phidgets.Events;
    
    namespace Robot
    {
        public partial class MainForm : Form
        {
    
            static InterfaceKit ifKit1; //Declare an InterfaceKit object
            static InterfaceKit ifKit2; //Declare an InterfaceKit object
            static InterfaceKit ifKit3; //Declare an InterfaceKit object
    
            static AdvancedServo left_arm; //Declare an servo object
            static AdvancedServo right_arm; //Declare an servo object
            static AdvancedServo eyes_and_wheels; //Declare an servo object
    
            static Phidgets.Encoder encoder; //Declare an encoder object
    
            static Accelerometer accel; //Declare an accelerometer object
    
    
            //int ifKit1SN = 117172;  //ifkit1 serial number 
            //int ifKit2SN = 100818;   //ifkit2 serial number 
            //int ifKit3SN = 000000;   //ifkit3 serial number 
    
            //int left_armSN = 99333;  //servo1 serial number
            //int right_armSN = 99364; //servo2 serial number
            //int eyes_and_wheelsSN = 170038 //servo3 serial number
    
            //int encoderSN = 000000; //encoder serial number
    
            //int accelSN = 159431; //servo1 serial number
    
            int armShoulderRotate = 0;
            int armShoulderLift = 1;
            int armElbow = 2;
            int armWristRotate = 3;
            int armWristLift = 4;
            int armGripper = 5;
    
            int eyeLeftYaw = 0;
            int eyeLeftLift = 2;
    
            int eyeRightYaw = 1;
            int eyeRightLift = 3;
    
            int wheelLeft = 6;
            int wheelRight = 7;
    
    
    
    
            // list of video devices
            FilterInfoCollection videoDevices;
            // form for cameras' movement
            MoveCamerasForm moveCamerasForm;
          
            ColorFiltering colorFilter = new ColorFiltering();
            GrayscaleBT709 grayFilter = new GrayscaleBT709();
            // use two blob counters, so the could run in parallel in two threads
            BlobCounter blobCounter1 = new BlobCounter();
            BlobCounter blobCounter2 = new BlobCounter();
    
            private AutoResetEvent camera1Acquired = null;
            private AutoResetEvent camera2Acquired = null;
            private Thread trackingThread = null;
    
            // object coordinates in both cameras
            private float x1, y1, x2, y2;
    
            private IntRange redRange = new IntRange(0, 255);
            private IntRange greenRange = new IntRange(0, 255);
            private IntRange blueRange = new IntRange(0, 255);
    
            
    
            public event EventHandler OnFilterUpdate;
    
            public MainForm()
            {
                InitializeComponent();
    
                // show device list
                try
                {
                    accel = new Accelerometer(); //Initialize the Accelerometer object
    
                    // enumerate video devices
                    videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    
                    if (videoDevices.Count == 0)
                    {
                        throw new Exception();
                    }
    
                    for (int i = 1, n = videoDevices.Count; i <= n; i++)
                    {
                        string cameraName = i + " : " + videoDevices[i - 1].Name;
    
                        camera1Combo.Items.Add(cameraName);
                        camera2Combo.Items.Add(cameraName);
                    }
    
                    // check cameras count
                    if (videoDevices.Count == 1)
                    {
                        camera2Combo.Items.Clear();
    
                        camera2Combo.Items.Add("Only one camera found");
                        camera2Combo.SelectedIndex = 0;
                        camera2Combo.Enabled = false;
                    }
                    else
                    {
                        camera2Combo.SelectedIndex = 1;
                    }
                    camera1Combo.SelectedIndex = 0;
                }
                catch
                {
                    startButton.Enabled = false;
    
                    camera1Combo.Items.Add("No cameras found");
                    camera2Combo.Items.Add("No cameras found");
    
                    camera1Combo.SelectedIndex = 0;
                    camera2Combo.SelectedIndex = 0;
    
                    camera1Combo.Enabled = false;
                    camera2Combo.Enabled = false;
                }
    
                //
                colorFilter.Red = new IntRange(0, 100);
                colorFilter.Green = new IntRange(0, 200);
                colorFilter.Blue = new IntRange(150, 255);  
                      
    
                // configure blob counters
                blobCounter1.MinWidth = 25;
                blobCounter1.MinHeight = 25;
                blobCounter1.FilterBlobs = true;
                blobCounter1.ObjectsOrder = ObjectsOrder.Size;
    
                blobCounter2.MinWidth = 25;
                blobCounter2.MinHeight = 25;
                blobCounter2.FilterBlobs = true;
                blobCounter2.ObjectsOrder = ObjectsOrder.Size;
            }
    
    
            private void MainForm_Load(object sender, EventArgs e)
            {
                accel.Attach += new AttachEventHandler(accel_Attach);
                accel.AccelerationChange += new AccelerationChangeEventHandler(accel_AccelerationChange);  //Hook the phidget spcific event handlers
               //accel.Error += new ErrorEventHandler(accel_Error);  //Hook the phidget spcific event handlers
    
                accel.open(159431);
    
                for (int i = 0; i < accel.axes.Count; i++)
                {
                    accel.axes[i].Sensitivity = 1.10;
                }
    
    
                StartCameras();
    
                UpdateObjectPicture(0, null);
                UpdateObjectPicture(1, null);
    
                startButton.Enabled = false;
                stopButton.Enabled = true;
    
                OnFilterUpdate += new EventHandler(OnFilterUpdate);
            }
    
           
    
          
    
            // On "Start" button click - start cameras
            private void startButton_Click(object sender, EventArgs e)
            {
                StartCameras();
    
                startButton.Enabled = false;
                stopButton.Enabled = true;
            }
    
            // On "Stop" button click - stop cameras
            private void stopButton_Click(object sender, EventArgs e)
            {
                StopCameras();
    
                startButton.Enabled = true;
                stopButton.Enabled = false;
            }
    
            // Start cameras
            private void StartCameras()
            {
                // create first video source
                VideoCaptureDevice videoSource1 = new VideoCaptureDevice(videoDevices[camera1Combo.SelectedIndex].MonikerString);
                videoSource1.DesiredFrameRate = 10;
    
                videoSourcePlayer1.VideoSource = videoSource1;
                videoSourcePlayer1.Start();
    
                // create second video source
                if (camera2Combo.Enabled == true)
                {
                    System.Threading.Thread.Sleep(500);
    
                    VideoCaptureDevice videoSource2 = new VideoCaptureDevice(videoDevices[camera2Combo.SelectedIndex].MonikerString);
                    videoSource2.DesiredFrameRate = 10;
    
                    videoSourcePlayer2.VideoSource = videoSource2;
                    videoSourcePlayer2.Start();
                }
    
                camera1Acquired = new AutoResetEvent(false);
                camera2Acquired = new AutoResetEvent(false);
                // start tracking thread
                trackingThread = new Thread(new ThreadStart(TrackingThread));
                trackingThread.Start();
            }
    
            // Stop cameras
            private void StopCameras()
            {
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer2.SignalToStop();
    
                videoSourcePlayer1.WaitForStop();
                videoSourcePlayer2.WaitForStop();
    
            
                    UpdateObjectPicture(0, null);
                    UpdateObjectPicture(1, null);
              
    
                if (trackingThread != null)
                {
                    // signal tracking thread to stop
                    x1 = y1 = x2 = y2 = -1;
                    camera1Acquired.Set();
                    camera2Acquired.Set();
    
                    trackingThread.Join();
                }
            }
                        
            //// Object filter properties are updated
            private void tuneObjectFilterForm_OnFilterUpdate(object sender, EventArgs eventArgs)
            {
                colorFilter.Red = RedRange;
                colorFilter.Green = GreenRange;
                colorFilter.Blue = BlueRange;
    
               
            }
    
            // Turn on/off object detection
            private void objectDetectionCheck_CheckedChanged(object sender, EventArgs e)
            {
                if ((!objectDetectionCheck.Checked))
                {
                    UpdateObjectPicture(0, null);
                    UpdateObjectPicture(1, null);
                }
            }
    
            // received frame from the 1st camera
            private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
            {
                if (objectDetectionCheck.Checked)
                {
                    Bitmap objectImage = colorFilter.Apply(image);
    
                    // lock image for further processing
                    BitmapData objectData = objectImage.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                        ImageLockMode.ReadOnly, image.PixelFormat);
    
                    // grayscaling
                    UnmanagedImage grayImage = grayFilter.Apply(new UnmanagedImage(objectData));
    
                    // unlock image
                    objectImage.UnlockBits(objectData);
    
                    // locate blobs 
                    blobCounter1.ProcessImage(grayImage);
                    Rectangle[] rects = blobCounter1.GetObjectsRectangles();
    
                    if (rects.Length > 0)
                    {
                        Rectangle objectRect = rects[0];
    
                        // draw rectangle around derected object
                        Graphics g = Graphics.FromImage(image);
    
                        using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 3))
                        {
                            g.DrawRectangle(pen, objectRect);
                        }
    
                        g.Dispose();
    
                        // get object's center coordinates relative to image center
                        lock (this)
                        {
                            x1 = (objectRect.Left + objectRect.Right - objectImage.Width) / 2;
                            y1 = (objectImage.Height - (objectRect.Top + objectRect.Bottom)) / 2;
                            // map to [-1, 1] range
                            x1 /= (objectImage.Width / 2);
                            y1 /= (objectImage.Height / 2);
    
                            camera1Acquired.Set();
                        }
                    }
    
                        UpdateObjectPicture(0, objectImage);
                }
            }
    
            // received frame from the 2nd camera
            private void videoSourcePlayer2_NewFrame(object sender, ref Bitmap image)
            {
                if (objectDetectionCheck.Checked)
                {
                    Bitmap objectImage = colorFilter.Apply(image);
    
                    // lock image for further processing
                    BitmapData objectData = objectImage.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                        ImageLockMode.ReadOnly, image.PixelFormat);
    
                    // grayscaling
                    UnmanagedImage grayImage = grayFilter.Apply(new UnmanagedImage(objectData));
    
                    // unlock image
                    objectImage.UnlockBits(objectData);
    
                    // locate blobs 
                    blobCounter2.ProcessImage(grayImage);
                    Rectangle[] rects = blobCounter2.GetObjectsRectangles();
    
                    if (rects.Length > 0)
                    {
                        Rectangle objectRect = rects[0];
    
                        // draw rectangle around derected object
                        Graphics g = Graphics.FromImage(image);
    
                        using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 3))
                        {
                            g.DrawRectangle(pen, objectRect);
                        }
    
                        g.Dispose();
    
                        // get object's center coordinates relative to image center
                        lock (this)
                        {
                            x2 = (objectRect.Left + objectRect.Right - objectImage.Width) / 2;
                            y2 = (objectImage.Height - (objectRect.Top + objectRect.Bottom)) / 2;
                            // map to [-1, 1] range
                            x2 /= (objectImage.Width / 2);
                            y2 /= (objectImage.Height / 2);
    
                            camera2Acquired.Set();
                        }
                    }
    
                   UpdateObjectPicture(1, objectImage);
                }
            }
    
            // Thread to track object
            private void TrackingThread()
            {
                float targetX = 0;
                float targetY = 0;
    
                while (true)
                {
                    camera1Acquired.WaitOne();
                    camera2Acquired.WaitOne();
    
                    lock (this)
                    {
                        // stop the thread if it was signaled
                        if ((x1 == -1) && (y1 == -1) && (x2 == -1) && (y2 == -1))
                        {
                            break;
                        }
    
                        // get middle point
                        targetX = (x1 + x2) / 2;
                        targetY = (y1 + y2) / 2;
                    }
    
                    if (moveCamerasForm != null)
                    {
                        // run motors for the specified amount of degrees
                        moveCamerasForm.RunMotors(2 * targetX, -2 * targetY);
                    }
                }
            }
    
           
    
            // Update object's picture
            public void UpdateObjectPicture(int objectNumber, Bitmap picture)
            {
                System.Drawing.Image oldPicture = null;
    
                switch (objectNumber)
                {
                    case 0:
                        oldPicture = pictureBox1.Image;
                        pictureBox1.Image = picture;
                        break;
                    case 1:
                        oldPicture = pictureBox2.Image;
                        pictureBox2.Image = picture;
                        break;
                }
    
                if (oldPicture != null)
                {
                    oldPicture.Dispose();
                }
            }
            // Red range
            public IntRange RedRange
            {
                get { return redRange; }
                set
                {
                    redRange = value;
                    redSlider.Min = value.Min;
                    redSlider.Max = value.Max;
                }
            }
            // Green range
            public IntRange GreenRange
            {
                get { return greenRange; }
                set
                {
                    greenRange = value;
                    greenSlider.Min = value.Min;
                    greenSlider.Max = value.Max;
                }
            }
            // Blue range
            public IntRange BlueRange
            {
                get { return blueRange; }
                set
                {
                    blueRange = value;
                    blueSlider.Min = value.Min;
                    blueSlider.Max = value.Max;
                }
            }
    
            // Red range was changed
            private void redSlider_ValuesChanged(object sender, EventArgs e)
            {
                redRange.Min = redSlider.Min;
                redRange.Max = redSlider.Max;
    
                if (OnFilterUpdate != null)
                    OnFilterUpdate(this, null);
            }
    
    
            // Green range was changed
            private void greenSlider_ValuesChanged(object sender, EventArgs e)
            {
                greenRange.Min = greenSlider.Min;
                greenRange.Max = greenSlider.Max;
    
                if (OnFilterUpdate != null)
                    OnFilterUpdate(this, null);
            }
    
            // Blue range was changed
            private void blueSlider_ValuesChanged(object sender, EventArgs e)
            {
                blueRange.Min = blueSlider.Min;
                blueRange.Max = blueSlider.Max;
    
                if (OnFilterUpdate != null)
                    OnFilterUpdate(this, null);
            }
    
    
            // Main form closing - stop cameras
            private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
            {
                StopCameras();
            }
    
            //Acceleration change event handler...Display which axis the device is accelerating in as well as the measured acceleration value
            static void accel_AccelerationChange(object sender, AccelerationChangeEventArgs e)
            {
               // Console.WriteLine("Axes {0} Acceleration {1}", e.Index, e.Acceleration);
                //if (e.Index == 0)
    
                //if (e.Acceleration >= 0.03)
                //    Console.WriteLine("tilt left");
    
                //if (e.Index == 1)
    
                //    if (e.Acceleration >= 0.03)
                //        Console.WriteLine("tilt right");
                //if (e.Index == 2)
    
                //    if (e.Acceleration >= 0.03)
                //        Console.WriteLine("tilt up");
                switch (e.Index)
                {
                    case 0: //1
                        
                        textBox1.Text = e.Acceleration.ToString();
                        break;
                    case 1:
                        textBox2.Text = e.Acceleration.ToString();
                        break;
                    case 2: //0
                        textBox3.Text = e.Acceleration.ToString();
                        break;
                }
            }
    
            //Attach event handler...Display the serial number of the attached 
            //accelerometer to the console
            static void accel_Attach(object sender, AttachEventArgs e)
            {
    
    
                Accelerometer attached = (Accelerometer)sender;
    
    
                try
                {
                    attached.axes[0].Sensitivity = 0.19;
                    attached.axes[1].Sensitivity = 0.19;
                    if (attached.axes.Count == 3)
                        attached.axes[2].Sensitivity = 0.19;
    
    
    
                }
                catch (PhidgetException ex)
                {
                    MessageBox.Show(ex.Description);
                }
            } 
            
        }
    }
    the error is on textBox1 - 3 instead of tbAccel0-2 {I couldn't change the names -is it part of the same problem?)

    Can somebody help?
    Last edited by Niheel; Jan 17 '11, 02:40 PM. Reason: please provide all your details in the question.
  • Samuel Jones
    New Member
    • Jan 2011
    • 48

    #2
    can we have a snippet of your code, to see what you mean?

    Comment

    • mrcw
      New Member
      • Nov 2008
      • 82

      #3
      I only get this error when I put two working programs together

      Comment

      • Samuel Jones
        New Member
        • Jan 2011
        • 48

        #4
        First things first: Snippet = Relevant part of code. Not full code.

        If your using Visual Studio, right click on 'InitializeComp onent();' and click 'Go to definition', then post the contents ONLY for the three textboxes.

        If you can't find them, that would be your problem.

        Otherwise it may be something in the code that you will post.

        Comment

        • mrcw
          New Member
          • Nov 2008
          • 82

          #5
          sorry about all the code. Is this what you mean
          Code:
          this.tbAccel1 = new System.Windows.Forms.TextBox();
                      this.tbAccel3 = new System.Windows.Forms.TextBox();
                      this.tbAccel2 = new System.Windows.Forms.TextBox();
          I confirm that the three textboxes are on the form design and their names are as stated. Also this only seems to happen with the accelerometer.

          Comment

          • Samuel Jones
            New Member
            • Jan 2011
            • 48

            #6
            Ok. I dont know whats wrong. code looks fine.

            Attach the project it a zip file to a post and ill have a deeper look.

            (Under post box, click 'Go Advanced', there should be a attachments box.)

            Comment

            • mrcw
              New Member
              • Nov 2008
              • 82

              #7
              not sure I've zipped it up properly

              error commented out (see line 1655)

              looks a bit messy remember it wip

              if you get chance fix warnings about obsolete

              Eventually working towards robot on wheels with two webcams for eyes and two grippers that will identify a shape of a certain colour

              thanks
              Attached Files

              Comment

              • Samuel Jones
                New Member
                • Jan 2011
                • 48

                #8
                Sorry it took so long to reply, computer was out of action.

                Ok, i looked at the file, compiled it and interestingly enough, i didn't get any errors.

                Looking at your form, it is very confusing and messy.

                As such i actually found you have textboxes named textbox0 - textbox8, all over the place. My suggestion is to clean up the form using tableLayoutPane ls within the groupboxes, then naming every textbox a unique name. similar to the tbAccel boxes. On that note your tbAccel boxes are numbered 0-2 in contrary to above post.

                After that, see if you get errors.

                Loving the robot idea. (I'm studying robotics engineering)

                Sam.

                Comment

                • mrcw
                  New Member
                  • Nov 2008
                  • 82

                  #9
                  I put a new hard disk in my computer yesterday evening and reloaded VS2010, ran the program and didn't get any errors either - I think it must have been a problem with the VS2010 installation. I'm an electronics engineer, I much prefer repairing radars and such. my programming skills could be better. Thanks for your help, good luck with the course

                  Comment

                  Working...