串行数据和System.NullReferenceException错误

时间:2015-06-04 13:25:42

标签: c# winforms serial-port

我正在设计一个Wndows表单应用程序,用于显示通过USB从露水加热器发送到笔记本电脑的串行数据。

当我收到任何数据时,我得到一个"类型' System.NullReferenceException'发生在System.Windows.Forms.dll中但未在用户代码中处理"错误。

以前我的代码工作正常,我不知道是什么造成了这种情况。

如果有人能够将错误翻译成外行人的条款以帮助我理解它并提出可能的解决方案,那么我将非常感激不尽。谢谢。

    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();
    }              
}

}

0 个答案:

没有答案