日期:2014-05-18  浏览次数:20962 次

弹出对话框显示数据,不弹出不显示
我现在做的一个电子秤串口程序。就是把称出来的数据显示在窗体上,在保存在Excel里面。
现在问题是我在接收数据的时候用MessageBox.Show(a)弹出接收的数据(a是接收的数据) 它就会显示在窗体上面。
如果不用MessageBox.Show(a) 它就不会显示在窗体上面。请问这是什么问题?
 #region 打开串口
  private void btnStart_Click(object sender, EventArgs e)
  {
  if (StartBool == false)
  {
  try
  {
  this.ClosingBool = false;//是否正在关闭串口
  this.Listening = false;//是否正在接收数据
  this.StartBool = true;

  this.txtReceiveData.Text = "";
  this.serialPort1.PortName = "COM1";
  this.serialPort1.BaudRate = 9600;
  this.serialPort1.DataBits = 8;
  this.serialPort1.Parity = System.IO.Ports.Parity.None;
  this.serialPort1.StopBits = System.IO.Ports.StopBits.One;

  if (this.serialPort1.IsOpen == false)
  {
  this.serialPort1.Open();
  MessageBox.Show("打开串口成功!");
  this.btnStop.Enabled = true;
  this.btnStart.Enabled = false;
  }
  }
  catch
  {
  if (this.serialPort1.IsOpen == true)
  {
  this.serialPort1.Close();
  }
  MessageBox.Show("打开串口失败");
  }
  }
  } 
  #endregion

 #region 读取数据
  private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  {
  if (ClosingBool) return; //如果正在关闭,忽略关闭操作,尽快的完成本次数据的读取
  try
  {
  Listening = true; //设置标记,说明我现在开始读取数据
  int n = this.serialPort1.BytesToRead;
  byte[] buf = new byte[n];
  this.serialPort1.Read(buf, 0, n);
  this.txtReceiveData.Invoke((EventHandler)(delegate
  {
  string receiveData = Encoding.ASCII.GetString(buf);
  string[] aaa = receiveData.Split(new char[] { '\n' });
  //MessageBox.Show(receiveData.ToString());
  if (receiveData.Length == 8)
  {
  Data2 = "DATA:20";
  }
  if (aaa.Length == 6 && receiveData.Contains("NW:") && aaa[3].Contains(".")==true)
  {
  Data = Data2 + aaa[0].ToString();
  NO = aaa[1].ToString();
  GW = aaa[2].ToString();
  NW = aaa[3].ToString();

  DataRow d = dtable.NewRow();
  d["Data"] = Data;
  d["NO"] = NO;
  d["GW"] = GW;
  d["NW"] = NW;
  dtable.Rows.Add(d);
  }

  if (Data.Contains("DATA:") == true && Data.Length > 5)