Code Bye

C#异常未将对象引用应用到对象的实例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Collections;
using System.Data.OleDb;

namespace COM_Demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

sp.DataReceived +=new SerialDataReceivedEventHandler(sp_DataReceived);//这句出现错误
CheckForIllegalCrossThreadCalls = false;

}
SerialPort sp = null;
private void button1_Click(object sender, EventArgs e)
{
sp = new SerialPort();
sp.PortName = “COM1”;//串口编号????????????
sp.BaudRate?=?9600;//波特率?????????????
sp.StopBits?=?StopBits.One;//?????????????
sp.DataBits?=?8;//?
sp.Parity = Parity.Even;//设置串口属性????????????
sp.Open();//打开串口
}

private void button2_Click(object sender, EventArgs e)
{
sp.WriteLine(textBox1.Text);//往串口写数据?
}

private void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
string str;
str = sp.ReadLine();
richTextBox1.Text += str;

}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

}

private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = “接收数据”;
saveFileDialog1.Filter = “txt files (*.txt)|*.txt”;
if (richTextBox1.Text != null)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.TextTextOleObjs);
}
}
}

}
}


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C#异常未将对象引用应用到对象的实例