0

I am designing a Wndows form app to display serial data sent via USB from a dew heater to my laptop.

when I receive any data I am getting a "An exception of type 'System.NullReferenceException' occurred in System.Windows.Forms.dll but was not handled in user code" error.

Previously my code worked OK and I am at a loss as to what is causing this.

If anybody could translate the error into layman's terms to help me understand it and come up with a possible solution I would be much obliged. Thanks.

    string rxString;

    public RxTxV2WFA()
    {
        InitializeComponent();

        timer1.Start();

        var ports = SerialPort.GetPortNames();
        cbCommPort.DataSource = ports;

        tbPortStatus.Text = "Port Closed";
    }

    private SerialPort myport;

    private void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        this.Invoke(new EventHandler(DisplayText));
        rxString = myport.ReadExisting();
    } 

    private void DisplayText(object sender, EventArgs e)
    {
        tbRxString.AppendText(rxString);
        tbRxTime.Text = DateTime.Now.ToString();     
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        myport = new SerialPort();
        myport.PortName = (cbCommPort.Text);
        myport.BaudRate = 9600;
        myport.Parity = Parity.None;
        myport.DataBits = 8;
        myport.StopBits = StopBits.One;
        myport.Open();
        myport.DataReceived += myPort_DataReceived;

        btnStart.Enabled = false;
        btnStop.Enabled = true;

        tbPortStatus.Text = "Port Open";
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        myport.Close();

        btnStart.Enabled = true;
        btnStop.Enabled = false;

        tbPortStatus.Text = "Port Closed";
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        DateTime dateTime = DateTime.Now;
        this.lTime.Text = dateTime.ToString();
    }

    private void btnAbout_Click(object sender, EventArgs e)
    {
        MessageBox.Show("2.02", "Version: ", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    private void btnGotoGraph_Click(object sender, EventArgs e)
    {
        Graph g1 = new Graph();
        g1.Show();
    }              
}

}

Vincent F
  • 371
  • 3
  • 17
Macko
  • 47
  • 5
  • "Previously my code worked OK" - so start by identifying what has *changed* between when it worked and now. – Damien_The_Unbeliever Jun 04 '15 at 13:29
  • Have you debugged your code to find out exactly where in your code the error is occurring? – Fred Jun 04 '15 at 13:30
  • It is an inevitable crash with this code. You must call Invoke() **after** setting the rxString variable. Further improve this code by using BeginInvoke instead so your program won't deadlock and writing a smarter DisplayText() method that takes a string argument so you don't have a threading race bug. – Hans Passant Jun 04 '15 at 13:30

0 Answers0